#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define TURE 1
#define FALSE 0
typedef int Status;
#define STACK_INIT_SIZE 10
#define STACK_INCREMENT 5
struct SqStack{
SElemType *base;
SElemType *top;
int stacksize;
};
void InitStack(SqStack &S){
if(!(S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType))))
exit(OVERFLOW);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
void DestroyStack(SqStack &S){
free(S.base);
S.base = NULL;
S.top = NULL;
S.stacksize = 0;
}
void ClearStack(SqStack &S){
S.top = S.base;
}
Status StackEmpty(SqStack S){
if(S.top == S.base)
return TURE;
return FALSE;
}
int StackLength(SqStack S){
return S.top - S.base;
}
Status GetTop(SqStack S, SElemType &e){
if(S.top > S.base){
e = *(S.top - 1);
return OK;
}
return ERROR;
}
void Push(SqStack &S, SElemType e){
if(S.top - S.base == S.stacksize){
S.base = (SElemType *)realloc( S.base, ( S.stacksize + STACK_INCREMENT) * sizeof(SElemType));
if(!S.base)
exit(OVERFLOW);
S.top = S.base + S.stacksize;
S.stacksize += STACK_INCREMENT;
}
*(S.top)++ = e;
}
Status Pop(SqStack &S, SElemType &e){
if(S.top == S.base)
return ERROR;
e = *--S.top;
return OK;
}
void StackTraverse(SqStack S, void(*visit) (SElemType)){
while(S.top > S.base)
visit(*S.base++);
printf("\n");
}
#include <iostream>
#include "constant.h"
typedef int SElemType;
#include "SqStack.h"
#include "SqStack_Operation.cpp"
using namespace std;
void print(SElemType c){
cout << c << ' ';
}
int main() {
SqStack S;
int e;
InitStack(S);
for(int i = 1; i <= 10; i ++)
Push( S, i);
cout << "stack is " << endl;
StackTraverse(S, print);
cout << "StackLength is " << StackLength( S) << endl;
cout << "S.stacksize is " << S.stacksize << endl;
GetTop( S, e);
cout << "Top is " << e << endl << endl;
Push( S, 11);
cout << "after Push 11" << endl;
cout << "stack is " << endl;
StackTraverse(S, print);
cout << "StackLength is " << StackLength( S) << endl;
cout << "S.stacksize is " << S.stacksize << endl;
GetTop( S, e);
cout << "Top is " << e << endl << endl;
Pop( S, e);
cout << "after Pop" << endl;
cout << "stack is " << endl;
StackTraverse(S, print);
cout << "StackLength is " << StackLength( S) << endl;
cout << "S.stacksize is " << S.stacksize << endl;
GetTop( S, e);
cout << "Top is " << e << endl << endl;
ClearStack( S);
cout << "after ClearStack" << endl;
cout << "stack is emtpy? (1 YES, 2 NO)" << endl << StackEmpty( S) << endl << endl;
DestroyStack( S);
cout << "after Destroy" << endl;
printf("S.top = %d, S.base = %d, S.stacksize = %d", S.top, S.base, S.stacksize);
cout << endl;
return 0;
}