1 #include <stdio.h>
2 #include <stdlib.h>
3
4 // 定义栈的结构体
5 typedef struct S
6 {
7 int data;
8 struct S *next;
9 } S, *SList;
10
11 // 初始化
12 void init(SList &top)
13 {
14 top = (S *)malloc(sizeof(S));
15 top->next = NULL;
16 }
17 // 压栈
18 bool push(SList top, int e)
19 {
20 //if无剩余可分配内存, 返回false
21 SList p = (S *)malloc(sizeof(S));
22 p->data = e;
23 p->next = top->next;
24 top->next = p;
25 return true;
26 }
27 // 弹栈
28 bool pop(SList top, int &e)
29 {
30 if (top->next == NULL)
31 return false;
32 SList p = (S *)malloc(sizeof(S));
33 p = top->next;
34 e = p->data;
35 top->next = p->next;
36 free(p);
37 return true;
38 }
39 // 判断栈是否为空
40 bool empty(SList top)
41 {
42 if (top->next == NULL)
43 return true;
44 return false;
45 }
46 // 遍历打印栈
47 void print(SList top)
48 {
49 SList p = (S *)malloc(sizeof(S));
50 p = top->next;
51 while (p != NULL)
52 {
53 printf("%d ", p->data);
54 p = p->next;
55 }
56 printf("\n");
57 }
58 int main()
59 {
60 SList top;
61 int x;
62 init(top);
63 printf("判断栈是否为空 %d\n", empty(top));
64 printf("空栈能否pop() %d\n", pop(top, x));
65 push(top, 10);
66 push(top, 9);
67 push(top, 8);
68 push(top, 7);
69 push(top, 6);
70 // 栈不为空时遍历打印栈中内容
71 print(top);
72 if(pop(top, x))
73 {
74 printf("%d\n", x);
75 }
76 return 0;
77 }