栈的基本运算
InitStack(&S): 初始化栈S
StackEmpty(): 判断栈是否为空
Push(e): 将元素e放入栈顶
Pop(e): 移走栈顶的元素,同时由e带回该元素的值
Gettop(): 获取栈顶的元素,但不从栈中移走
#include <stdio.h>
#include <stdlib.h>
# define STACK_INIT_SIZE 100
# define STACKINCREMENT 10
typedef struct {
int *base;
int *top;
int stacksize;
}SqStack;
bool InitStack(SqStack &S)
{
S.base = (int *)malloc(STACK_INIT_SIZE*sizeof(int));
if(!S.base)
return false;
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return true;
}
bool 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)
return false;
S.top = S.base + S.stacksize;
S.stacksize = S.stacksize + STACKINCREMENT;
}
*S.top = e;
S.top++;
return true;
}
bool StackEmpty(SqStack &S){
if(S.base == S.top)
return true;
else
return false;
}
int Gettop(SqStack &S){
int *p = S.top -1;
int e = *p;
return e;
}
int Pop(SqStack &S){
int e = *--S.top;
return e;
}
int main(){
SqStack sq;
InitStack(sq);
Push(sq,1);
Push(sq,2);
if(StackEmpty(sq))
printf("空\n");
else
printf("非空\n");
printf("栈顶元素:%d\n",Gettop(sq));
printf("元素出栈:%d\n",Pop(sq));
printf("元素出栈:%d\n",Pop(sq));
if(StackEmpty(sq))
printf("空\n");
else
printf("非空\n");
return 0;
}