1 #include <stdio.h>
2 #include <stdlib.h>
3 typedef int datatype;
4 typedef struct stack_linked
5 {
6 int data;
7 struct stack_linked * next;
8 }slinked,*slinked_p;
9 slinked_p stack_creat();
10 int stack_push(slinked_p S,datatype value);
11 int stack_empty(slinked_p S);
12 datatype stack_pop(slinked_p S);
13 int stack_pop1(slinked_p S,datatype *value);
14 int stack_top(slinked_p S);
15 void stack_clear(slinked_p S);
16 void stack_clear(slinked_p S);
17 void stack_free(slinked_p S);
18 int main(int argc, const char *argv[])
19 {
20 int value;
21 slinked_p S = stack_creat();
22 if(NULL == S)
23 {
24 printf("函数调用失败\n");
25 return -1;
26 }
27 stack_push(S,1);
28 stack_push(S,2);
29 stack_push(S,3);
30 stack_push(S,4);
31 //printf("top = %d\n",stack_pop(S));
32 stack_pop1(S,&value);
33 printf("pop = %d\n",value);
34 printf("top = %d\n",stack_top(S));
35 stack_clear(S);
36 stack_free(S);
37 return 0;
38 }
39
40 slinked_p stack_creat()
41 {
42 slinked_p S = (slinked_p)malloc(sizeof(slinked));
43 if(S == NULL)
44 {
45 printf("空间开辟失败\n");
46 return NULL;
47 }
48 S->next = NULL;
49 return S;
50 }
51
52 int stack_push(slinked_p S,datatype value)
53 {
54 slinked_p p = (slinked_p)malloc(sizeof(slinked));
55 if(NULL == p)
56 {
57 printf("内存空间开辟失败\n");
58 return -1;
59 }
60 p->next = S->next;
61 S->next = p;
62 p->data = value;
63 return 0;
64 }
65
66 datatype stack_pop(slinked_p S)
67 {
68 if(stack_empty(S))
69 {
70 printf("栈空间为空\n");
71 return -1;
72 }
73 slinked_p p = S->next;
74 int value = p->data;
75 S->next = p->next;
76 free(p);
77 p = NULL;
78 return value;
79 }
80 int stack_empty(slinked_p S)
81 {
82 return S->next == NULL?1:0;
83 }
84
85 int stack_pop1(slinked_p S,datatype *value)
86 {
87 if(stack_empty(S))
88 {
89 printf("栈空间为空\n");
90 return -1;
91 }
92 slinked_p p = S->next;
93 *value = p->data;
94 S->next = p->next;
95 free(p);
96 p = NULL;
97 return 0;
98 }
99 //取栈顶元素
100 int stack_top(slinked_p S)
101 {
102 return S->next->data;
103 }
104
105 //清空栈
106 void stack_clear(slinked_p S)
107 {
108 while(!stack_empty(S))
109 {
110 printf("%d ",stack_pop(S));
111 }
112 putchar(10);
113 }
114
115 //free栈
116
117 void stack_free(slinked_p S)
118 {
119 stack_clear(S);
120 free(S);
121 S = NULL;
122 }