数据结构 顺序栈基本操作

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <math.h>
  4 
  5 #define STACK_INIT_SIZE 1
  6 #define STACKINCREMENT   2
  7 #define    OK      1
  8 #define    FALSE    0
  9 #define   TRUE     1
 10 #define    ERROR    0
 11 
 12 typedef int Status;
 13 typedef int SElemType;
 14 
 15 typedef struct SqStack
 16 {
 17     SElemType    *base;
 18     SElemType    *top;
 19     int    stacksize;
 20 }SqStack;
 21 
 22 Status InitStack(SqStack *S)
 23 {
 24     (*S).base = (SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
 25     if(!(*S).base)
 26         exit(OVERFLOW);
 27     (*S).top = (*S).base;
 28     (*S).stacksize = STACK_INIT_SIZE;
 29     return OK;
 30 }
 31 
 32  Status DestroyStack(SqStack *S)
 33  { 
 34    free((*S).base);
 35    (*S).base=NULL;
 36    (*S).top=NULL;
 37    (*S).stacksize=0;
 38    return OK;
 39  }
 40 
 41  Status ClearStack(SqStack *S)
 42  {
 43    (*S).top=(*S).base;
 44    return OK;
 45  }
 46 
 47  int StackLength(SqStack S)
 48  { 
 49    return S.top-S.base;
 50  }
 51 
 52  Status StackEmpty(SqStack S)
 53  { 
 54    if(S.top==S.base)
 55      return TRUE;
 56    else
 57      return FALSE;
 58  }
 59 
 60  Status GetTop(SqStack S,SElemType *e)
 61  { 
 62    if(S.top>S.base)
 63    {
 64      *e=*(S.top-1);
 65      return OK;
 66    }
 67    else
 68      return ERROR;
 69  }
 70 
 71  Status Push(SqStack *S,SElemType e)
 72  { 
 73    if((*S).top-(*S).base>=(*S).stacksize) 
 74    {
 75      (*S).base=(SElemType *)realloc((*S).base,((*S).stacksize+STACKINCREMENT)*sizeof(SElemType));
 76      if(!(*S).base)
 77        exit(OVERFLOW); 
 78      (*S).top=(*S).base+(*S).stacksize;
 79      (*S).stacksize+=STACKINCREMENT;
 80    }
 81    *((*S).top)++=e;
 82    return OK;
 83  }
 84 
 85  Status Pop(SqStack *S,SElemType *e)
 86  {
 87    if((*S).top==(*S).base)
 88      return ERROR;
 89    *e=*--(*S).top;
 90    return OK;
 91  }
 92 
 93  Status StackTraverse(SqStack S,Status(*visit)(SElemType))
 94  { 
 95    while(S.top>S.base)
 96      visit(*S.base++);
 97    printf("\n");
 98    return OK;
 99  }
100 
101   Status visit(SElemType c)
102  {
103    printf("%d ",c);
104    return OK;
105  }
106 
107  void main()
108  {
109    int j;
110    SqStack s;
111    SElemType e;
112    if(InitStack(&s)==OK)
113      for(j=1;j<=12;j++)
114        Push(&s,j);
115    printf("栈中元素依次为:");
116    StackTraverse(s,visit);
117    Pop(&s,&e);
118    printf("弹出的栈顶元素 e=%d\n",e);
119    printf("栈空否:%d(1:空 0:否)\n",StackEmpty(s));
120    GetTop(s,&e);
121    printf("栈顶元素 e=%d 栈的长度为%d\n",e,StackLength(s));
122    ClearStack(&s);
123    printf("清空栈后,栈空否:%d(1:空 0:否)\n",StackEmpty(s));
124    DestroyStack(&s);
125    printf("销毁栈后,s.top=%u s.base=%u s.stacksize=%d\n",s.top,s.base, s.stacksize);
126  }

 

posted on 2012-04-27 15:49  QLinux  阅读(412)  评论(0编辑  收藏  举报

导航