栈的实现

复习使用C语言实现栈

PS:其中有一个动态增加内存的方法,要注意

 1 #define STACK_INIT_SIZE 100
 2 #define STACKINCREMENT 100
 3 
 4 typedef struct{
 5     SElemType *base;
 6     SElemType *top;
 7 }SqStack;
 8 
 9 status InitStact(SqStack %S){
10     S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
11     if(!S.base)
12         exit(OVERFLOW);
13     S.top = S.base;
14     S.stacksize = STACK_INIT_SIZE;
15     return OK;
16 }
17 
18 status GetTop(SqStack S,SElemType &e){  //top元素保存在e中
19     if(S.top == S.base)
20         return ERROR;
21     e = *(S.top-1);
22     return OK;
23 }
24 
25 status Push(SqStack &S,SElemType e){
26     if(S.top - S.base >= S.stacksize){  //栈已满
27         //动态增加内存
28         S.base = (SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
29         if(!S.base)
30             exit(OVERFLOW);
31         S.top = S.base + S.stacksize;
32         S.stacksize + = STACKINCREMENT;
33     }
34     *S.top++ = e;
35     return OK;
36 }
37 
38 status Pop(SqStack &S,SElemType &e){
39     if(S.top == S.base)
40         return ERROR;
41     e = * --S.top;
42     return Ok;
43 }

 

posted @ 2015-04-10 22:41  某某璀  阅读(219)  评论(0编辑  收藏  举报
levels of contents