/*
对栈实现初始化,插入栈顶元素,删除栈顶元素,遍历栈,清空栈等基本操作
*/
1 #include <stdio.h>
2 #include <malloc.h>
3 #include <stdlib.h>
4
5 #define true 1
6 #define false 0
7
8
9 typedef struct Node
10 {
11 int data;
12 struct Node *pNext;
13 }NODE, *PNODE;
14
15 typedef struct Stack
16 {
17 PNODE pTop;
18 PNODE pBottom;
19 }STACK, *PSTACK;
20
21 void init(PSTACK pS);
22 void push(PSTACK pS, int val);
23 void traverse(PSTACK pS);
24 int pop(PSTACK pS , int *val);
25 void clear(PSTACK pS);
26 int empty(PSTACK pS);
27
28 int main(void)
29 {
30 STACK S ;
31 int val;
32 int i;
33
34 init(&S);
35
36 push(&S,1);
37 push(&S,2);
38 push(&S,3);
39 push(&S,4);
40 push(&S,5);
41 push(&S,6);
42
43 traverse(&S);
44
45 if(pop(&S ,&val))
46 {
47 printf("遍历成功,出栈元素为%d\n",val);
48 }
49 else
50 {
51 printf("出栈失败!\n");
52 }
53 traverse(&S);
54
55 clear(&S);
56
57 traverse(&S);
58
59 return 0 ;
60 }
61
62 //栈的初始化
63 void init(PSTACK pS)
64 {
65 pS -> pTop = (PNODE)malloc(sizeof(NODE));
66
67 if(NULL == pS -> pTop)
68 {
69 printf("动态内存分配失败!");
70 exit(-1);
71 }
72 else
73 {
74 pS -> pBottom = pS -> pTop;
75 pS -> pTop -> pNext = NULL;
76 }
77
78 return ;
79 }
80
81 //插入元素到栈顶
82 void push(PSTACK pS , int val)
83 {
84 PNODE pNew = (PNODE)malloc(sizeof(NODE));
85
86 pNew -> data = val;
87 pNew -> pNext = pS -> pTop;
88 pS -> pTop = pNew;
89
90 return ;
91 }
92
93 //遍历栈S
94 void traverse(PSTACK pS)
95 {
96 PNODE p = pS -> pTop;
97
98 printf("栈内元素为:");
99 while(p != pS -> pBottom)
100 {
101 printf("%d\t", p -> data);
102 p = p -> pNext;
103 }
104
105 printf("\n");
106 return ;
107 }
108
109 //判断栈是否为空
110 int empty(PSTACK pS)
111 {
112 if(pS -> pTop == pS -> pBottom)
113 {
114 return true;
115 }
116 else
117 return false;
118 }
119
120 //删除栈顶元素并将其值赋给*val
121 int pop(PSTACK pS , int *val)
122 {
123 if(empty(pS))
124 {
125 return false;
126 }
127 else
128 {
129 PNODE r = pS -> pTop;
130 *val = r -> data;
131 pS -> pTop = r -> pNext;
132 free(r);
133 r = NULL;
134 }
135 }
136
137 //清空栈S
138 void clear(PSTACK pS)
139 {
140 if(empty(pS))
141 {
142 return;
143 }
144 else
145 {
146 PNODE p = pS -> pTop;
147 PNODE q = NULL;
148
149 while(p != pS -> pBottom)
150 {
151 q = p -> pNext;
152 free(p);
153 p = q ;
154 }
155
156 pS -> pTop = pS -> pBottom;
157
158 return;
159 }
160 }