首页 > 其他 > 详细

数据结构-栈

时间:2018-09-20 00:26:39      阅读:241      评论:0      收藏:0      [点我收藏+]
  1 #include <stdio.h>
  2 #include <malloc.h>
  3 #include <stdlib.h>
  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;
 14     PNODE pBottom;
 15 }STACK,*PSTACK;
 16 
 17 void init(PSTACK);
 18 void push(PSTACK, int);
 19 bool pop(PSTACK, int*);
 20 void clear(PSTACK pS);
 21 
 22 int main(void)
 23 {
 24     int val;
 25     STACK S;
 26     init(&S);
 27     push(&S,1);
 28     push(&S,2);
 29     pop(&S,&val);
 30     traverse(&S);
 31     clear(&S);
 32     return 0;
 33 }
 34 
 35 void init(PSTACK pS)
 36 {
 37     pS->pTop = (PNODE)malloc(sizeof(NODE));
 38     if (NULL == pS->pTop)
 39     {
 40         printf("malloc fail!");
 41         exit(-1);
 42     }
 43     else
 44     {
 45         pS->pBottom = pS->pTop;
 46         pS->pTop->pNext = NULL;
 47     }
 48 }
 49 
 50 
 51 void push(PSTACK pS, int val)
 52 {
 53     PNODE pNew = (PNODE)malloc(sizeof(NODE));
 54     if (NULL != pNew)
 55     {
 56         pNew->data = val;
 57         pNew->pNext = pS->pTop;
 58         pS->pTop = pNew;
 59     }
 60     return;
 61 }
 62 
 63 void traverse(PSTACK pS)
 64 {
 65     PNODE p = pS->pTop;
 66     while (p != pS->pBottom)
 67     {
 68         printf("%d", p->data);
 69         p=p->pNext;
 70     }
 71     printf("\n");
 72 }
 73 
 74 bool empty(PSTACK pS)
 75 {
 76     if (pS->pBottom == pS->pTop)
 77     {
 78         return true;
 79     }
 80     else
 81     {
 82         return false;
 83     }
 84 }
 85 
 86 bool pop(PSTACK pS, int *pVal)
 87 {
 88     if (empty(pS))
 89     {
 90         return false;
 91     }
 92     else
 93     {
 94         PNODE r = pS->pTop;
 95         *pVal = r->data;
 96         pS->pTop = r->pNext;
 97         free(r);
 98         r = NULL;
 99         return true;
100     }
101 }
102 
103 //清空
104 void clear(PSTACK pS)
105 {
106     if (empty(pS))
107     {
108         return;
109     }
110     else
111     {
112         PNODE p = pS->pTop;
113         PNODE q = NULL;
114         while (p != pS->pBottom)
115         {
116             q = p->pNext;
117             free(p);
118             p = q;
119         }
120     }
121     pS->pTop = pS->pBottom;
122 }

 

数据结构-栈

原文:https://www.cnblogs.com/hujianglang/p/9678213.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!