运行的过程,首先入栈四个元素,打印,接下来4入栈,再次打印,下面打印栈顶元素,最后栈顶元素出栈,再次打印
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct {
int *base;
int *top;
int stacksize;
}SqStack;
//初始化栈
int InitStack(SqStack &S) {
S.base = (int*)malloc(STACK_INIT_SIZE * sizeof(int));
if (!S.base) {
exit(-1);
}
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return 1;
} // InitStack
//获得栈顶元素
int GetTop(SqStack S,int &e) {
if (S.top == S.base)
{
return 0;
}
e = *(S.top-1);
return 1;
} // GetTop
//入栈
int Push (SqStack &S, int e) {
if (S.top - S.base >= S.stacksize) {
S.base = (int*)realloc(S.base,
(S.stacksize + STACKINCREMENT) * sizeof(int));
if (!S.base)
{
exit (-1);
}
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
* S.top ++ = e;
return 1;
} // Push
//出栈
int Pop (SqStack &S,int &e) {
if (S.top == S.base)
{
return 0;
}
e = *--S.top;
return 1;
} // Pop
//打印栈
void print(SqStack S) {
for(int i=1;i<=S.top-S.base;i++){
printf("%d \n",*(S.top-i));
}
}
int main(){
SqStack s;
InitStack(s);
printf("7,1,2,3依次入栈\n");
Push(s,7);
Push(s,1);
Push(s,2);
Push(s,3);
print(s);
printf("4入栈打印全部\n");
Push(s,4);
print(s);
int e;
GetTop(s,e);
printf("打印栈顶元素\n");
printf("%d \n",e);
printf("出栈后打印\n");
Pop(s,e);
print(s);
}