数据结构顺序栈:进栈、出栈、读栈等操作
#define MaxSize 10 //定义栈中元素的最大个数
typedef struct{
int data[MaxSize]; //静态数组存放栈中元素
int top; //栈顶指针
}SqStack;
//初始化栈
void InitStack(SqStack &S){
S.top = -1; //初始化栈顶指针
}
//判断栈是否为空
bool StackEmpty(SqStack S){
if(S.top == -1) //栈空
return true;
else //栈空
return false;
}
//进栈
bool Push(SqStack &S, int x){
if(S.top == MaxSize-1) //栈满
return false;
S.top = S.top + 1; //指针先加1
S.data[S.top] = x; //新元素入栈
//S.data[++S.top] = x; //上面两句也可合写成此句
return true;
}
//出栈
bool Pop(SqStack &s, ElemType &x){
if(S.top == -1)
return false;
x = S.data[S.top]; //栈顶元素先出栈
S.top = S.top-1; //指针再减1
//x = S.data[S.top--]; //上面两句也可合写成此句
return true;
}
//读栈顶元素
bool GetTop(SqStack S, ElemType &x){
if(S.top == -1) //栈空,报错
return false;
x = S.data[S.data]; //x记录栈顶元素
return true;
}
void testStack(){
SqStack S;
InitStack(S);
//...后续操作....
}
共享栈
#define MaxSize 10
typedef struct{
int data[MaxSize];
int top0;
int top1;
}ShStack;
//初始化栈
void InitStack(SqStack &S){
S.top0 = -1;
S.top1 = MaxSize;
}
//栈满的条件:top0+1 == top1;