链栈

链栈

  1 #include
  2 #include<malloc.h>
  3 #include
  4 
  5 typedef struct Node
  6 {
  7     int data;
  8     struct Node * pNext;
  9 }NODE, *PNODE;
 10 
 11 typedef struct Stack
 12 {
 13     PNODE pTop;   //top指针
 14     PNODE pBottom;    //bottom指针
 15 }STACK, *PSTACK;
 16 
 17 void init(PSTACK);
 18 void push(PSTACK,int);
 19 void traverse(PSTACK);
 20 bool is_empty(PSTACK);
 21 bool pop(PSTACK,int*);
 22 void clear(PSTACK);
 23 
 24 int main()
 25 {
 26     STACK S;  //STACK 等价于struct Stack
 27     int val;
 28 
 29     init(&S);   //目的是造出一个空栈
 30     printf("入栈元素是");
 31     push(&S,1);   //压栈
 32     push(&S,2);
 33     push(&S,3);
 34     push(&S,4);
 35     push(&S,5);
 36     traverse(&S);  //遍历输出
 37 
 38     if( pop(&S,&val) )
 39     {
 40         printf("出栈成功,出栈的元素是%d ",val);
 41     }
 42     else
 43     {
 44         printf("出栈失败!\n");
 45     }
 46     traverse(&S);  //遍历输出
 47 
 48     clear(&S);
 49     traverse(&S);  
 50     return 0;
 51 }
 52 
 53 void init(PSTACK pS)
 54 {
 55     pS->pTop = (PNODE)malloc(sizeof(NODE));
 56     if(NULL == pS->pTop)
 57     {
 58         printf("动态内存分配失败");
 59         exit(-1);
 60     }
 61     else
 62     {
 63         pS->pBottom = pS->pTop;
 64         pS->pTop->pNext = NULL;  //pS->Bottom->pNext = NULL;
 65     }
 66 }
 67 
 68 void push(PSTACK pS,int val)
 69 {
 70     PNODE pNew = (PNODE)malloc(sizeof(NODE));
 71 
 72     pNew->data = val;
 73     pNew->pNext = pS->pTop;  //pS->ptop能改成pS->pBottom
 74     pS->pTop = pNew;
 75     return;
 76 }
 77 
 78 void traverse(PSTACK pS)
 79 {
 80     PNODE p = pS->pTop;
 81 
 82     while(p != pS->pBottom)
 83     {
 84         printf("%d ",p->data);
 85         p = p->pNext;
 86     }
 87     printf("\n");
 88     return;
 89 }
 90 
 91 bool is_empty(PSTACK pS)
 92 {
 93     if(pS->pTop == pS->pBottom)
 94         return true;
 95     else
 96         return false;
 97 }
 98 
 99 bool pop(PSTACK pS,int *pVal)
100 {
101     if( is_empty(pS) )
102     {
103         return false;
104     }
105     else
106     {
107         PNODE r = pS->pTop;
108         *pVal = r->data;
109         pS->pTop = r->pNext;
110         free(r);
111         r = NULL;
112         return true;
113     }
114 }
115 
116 void clear(PSTACK pS)
117 {
118     if( is_empty(pS) )
119     {
120         return;
121     }
122     else
123     {
124         PNODE p = pS->pTop;
125         PNODE q = NULL;
126 
127         while(p != pS->pBottom)
128         {
129             q = p->pNext;
130             free(p);
131             p = q;
132         }
133         pS->pTop = pS->pBottom;
134     }
135     return;
136 }

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