#include <malloc.h>ide
#include <stdlib.h>測試
#define STACK_INIT_SIZE 10spa
#define STACK_INCREMENT_SIZE 10get
#define Status boolit
#define OK trueclass
#define ERROR falsegc
typedef int SElemType;top
typedef struct SqStack{tab
SElemType* top;di
SElemType* base;
int stackSize;
}SqStack,*pSqStack;
class Stack{
public:
Stack();
~Stack();
Status InitStack(SqStack &S);
Status DestroyStack(SqStack &S);
Status ClearStack(SqStack &S);
Status StackIsEmpty(SqStack &S);
Status StackLength(SqStack &S,int& len);
Status getTop(SqStack &S,SElemType& e);
Status push(SqStack &S,SElemType& e);
Status pop(SqStack &S,SElemType& e);
};
Stack::Stack(){
}
Stack::~Stack(){
}
/*
初始化棧
分配默認大小空間
*/
Status Stack::InitStack(SqStack &S){
S.base = (SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if (!S.base)
return ERROR;
S.top = S.base;
S.stackSize = STACK_INCREMENT_SIZE;
return OK;
}
/*
銷燬棧
默認分配的空間也會被回收
*/
Status Stack::DestroyStack(SqStack &S){
if (S.base)
free(S.base);
S.base = S.top = NULL;
return true;
}
/*
清空棧
邏輯上的清空
*/
Status Stack::ClearStack(SqStack &S){
if (!S.base)
return ERROR;
S.top = S.base;
}
/*
棧是否爲空
*/
Status Stack::StackIsEmpty(SqStack &S){
if (S.top == S.base) return OK;
return ERROR;
}
/*
棧的長度
*/
Status Stack::StackLength(SqStack &S,int& len){
if (S.top == S.base){
len = 0;
return ERROR;
}
len = (S.top - S.base)%(S.stackSize+1);
return OK;
}
/*
棧頂得值
*/
Status Stack::getTop(SqStack &S,SElemType& e){
if (S.top == S.base) return ERROR;
e = *(S.top-1);
return OK;
}
/*
壓棧
*/
Status Stack::push(SqStack &S,SElemType& e){
if (S.top - S.base >= S.stackSize)
{
//須要增長空間
S.base = (SElemType*)realloc(S.base,(S.stackSize+STACK_INCREMENT_SIZE)*sizeof(SElemType));
if (!S.base) return ERROR;
S.top = S.base+S.stackSize;
S.stackSize+=STACK_INCREMENT_SIZE;
}
*S.top++ = e;
return OK;
}
/*
出棧
*/
Status Stack::pop(SqStack &S,SElemType& e){
if (S.top == S.base)return ERROR;
e=*--S.top;
return OK;
}
/*
測試
*/
int _tmain(int argc, _TCHAR* argv[])
{
SqStack sq;
Stack* stack = new Stack();
stack->InitStack(sq);
if(stack->StackIsEmpty(sq))
printf("棧爲空,請push\n");
SElemType i = 0;
while(i++<30)
stack->push(sq,i);
if (stack->StackIsEmpty(sq))
printf("棧不爲空\n");
int len;
if (stack->StackLength(sq,len))
printf("棧的長度=%d\n",len);
SElemType e;
if (stack->getTop(sq,e))
printf("棧頂元素=%d\n",e);
i=0;
while (i++<len)
{
if (stack->pop(sq,e))
{
printf("棧頂元素%d=%d\n",i,e);
}
}
if (stack->StackIsEmpty(sq))
printf("棧爲空\n");
stack->ClearStack(sq);
stack->DestroyStack(sq);
if (NULL == sq.base)
{
printf("棧已銷燬\n");
}
if (stack)
{
delete stack;
}
getchar();
return 0;
}