首页 > 代码库 > 数据结构之堆栈

数据结构之堆栈

  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;  //PSTACK 等价于 struct STACK *
 16 
 17 void init(PSTACK);
 18 void push(PSTACK, int );
 19 void traverse(PSTACK);
 20 bool pop(PSTACK, int *);
 21 void clear(PSTACK pS);
 22 
 23 int main(void)
 24 {
 25     STACK S;  //STACK 等价于 struct Stack
 26     int val;
 27 
 28     init(&S);  //目的是造出一个空栈
 29     push(&S, 1); //压栈
 30     push(&S, 2);
 31     push(&S, 3);
 32     push(&S, 4);
 33     push(&S, 5);
 34     push(&S, 6);
 35     traverse(&S); //遍历输出
 36     
 37     clear(&S);
 38     //traverse(&S); //遍历输出
 39 
 40     if ( pop(&S, &val) )
 41     {
 42         printf("出栈成功,出栈的元素是%d\n", val);
 43     }
 44     else
 45     {
 46         printf("出栈失败!\n");
 47     }
 48 
 49     traverse(&S); //遍历输出
 50 
 51     return 0;
 52 }
 53 
 54 void init(PSTACK pS)
 55 {
 56     pS->pTop = (PNODE)malloc(sizeof(NODE));
 57     if (NULL == pS->pTop)
 58     {
 59         printf("动态内存分配失败!\n");
 60         exit(-1);
 61     }
 62     else
 63     {
 64         pS->pBottom = pS->pTop;
 65         pS->pTop->pNext = NULL; //pS->Bottom->pNext = NULL;
 66     }
 67 }
 68 
 69 void push(PSTACK pS, int val)
 70 {
 71     PNODE pNew = (PNODE)malloc(sizeof(NODE));
 72     
 73     pNew->data =http://www.mamicode.com/ val;
 74     pNew->pNext = pS->pTop; //pS->Top不能改成pS->Bottom
 75     pS->pTop = pNew;
 76 
 77     return;
 78 }
 79 
 80 void traverse(PSTACK pS)
 81 {
 82     PNODE p = pS->pTop;
 83 
 84     while (p != pS->pBottom)
 85     {
 86         printf("%d  ", p->data);
 87         p = p->pNext;
 88     }
 89     printf("\n");
 90 
 91     return;
 92 }
 93 
 94 bool empty(PSTACK pS)
 95 {
 96     if (pS->pTop == pS->pBottom)
 97         return true;
 98     else
 99         return false;
100 }
101 
102 //把pS所指向的栈出栈一次,并把出栈的元素存入pVal形参所指向的变量中,如果出栈失败,返回false,否则返回true
103 bool pop(PSTACK pS, int * pVal)
104 {
105     if ( empty(pS) ) //pS本身存放的就是S的地址
106     {
107         return false;
108     }
109     else
110     {
111         PNODE r = pS->pTop;
112         *pVal = r->data;
113         pS->pTop = r->pNext;
114         free(r);
115         r = NULL;
116 
117         return true;
118     }
119 }
120 
121 //clear清空
122 void clear(PSTACK pS)
123 {
124     if (empty(pS))
125     {
126         return;
127     }
128     else
129     {
130         PNODE p = pS->pTop;
131         PNODE q = NULL;
132 
133         while (p != pS->pBottom)
134         {
135             q = p->pNext;
136             free(p);
137             p = q;
138         }
139         pS->pTop = pS->pBottom;
140     }
141 }

 

数据结构之堆栈