(七)线性堆栈

/**************************************** 堆栈操作:<EMPTY><PUSH><POP><TOP> 用数组S[0,n-1]来实现一个至多有n个元素的栈。 STACK_EMPYT(S) //判断栈是否为空 if top[S]=-1 then return ture else return false PUSH(S,x) //将元素x压入栈中 if top[S]=n-1 then error "stack overflow" top[S] <—— top[S]+1 S[top[S]] <—— x POP(S) //从栈顶弹出一个元素 if STCK_EMPTY(S) then error "stack underflow" else top[S] <—— top[S]-1 return S[top[S]+1] top(S) //获取栈顶元素,但不弹出栈顶元素 if STCK_EMPTY(S) then error "stack underflow" return S[top[S]] ****************************************/ #include <stdio.h> #include <stdlib.h>
#define STACKSIZE 1024
#define MAX_INT ~(1<<31) typedef struct { int *data; int top; }stack; int stack_empty(stack *s) { return (s->top==-1); } void push(stack *s,int x) { if(s->top>=STACKSIZE-1) return; s->top++; s->data[s->top]=x; } int pop(stack *s) { if(stack_empty(s)) return MAX_INT; s->top--; return s->data[s->top+1]; } int top(stack *s) { if(stack_empty(s)) return MAX_INT; return s->data[s->top]; }
//初始化一个栈 stack
* init_stack(int size) { stack *pstack=(stack*)malloc(sizeof(stack)); pstack->data=(int*)malloc(size*sizeof(int)); pstack->top=-1; return pstack; }
//释放栈资源,在使用完栈后,调用此函数
void fini_stack(stack *pstack) { if(pstack->data) free(pstack->data); if(pstack) free(pstack); } int main() { stack *pstack=init_stack(STACKSIZE); int i; for(i=0;i<10;++i) push(pstack,i); for(i=0;i<=pstack->top;++i) printf("%d ",pstack->data[i]); pop(pstack); pop(pstack); printf("%d ",top(pstack)); for(i=0;i<=pstack->top;++i) printf("%d ",pstack->data[i]);
  fini_stack(pstack); }

 

你可能感兴趣的:(堆栈)