链式栈:
头文件:
1 #ifndef __LINK_STACK__
2 #define __LINK_STACK__
3 #include<stdio.h>
4 #include<stdlib.h>
5 typedef int datatype;
6 typedef struct Node
7 {
8 union
9 {
10 int len;
11 datatype data;
12 };
13 struct Node *next;
14 }Node;
15 typedef struct Lstack
16 {
17 Node *p;
18 }Lstack,*stack;
19
20 //建栈
21 stack stack_create();
22 //判空
23 int stack_empty(stack s);
24 //申请结点
25 Node *node_buy(datatype data);
26 //入栈
27 int push(stack s,datatype data);
28 //出栈
29 int pop(stack s);
30 //遍历栈
31 void stack_show(stack s);
32 //销毁栈
33 stack stack_delete(stack s);
37 #endif
功能函数:
1 #include"link_stack.h"
2 //建栈
3 stack stack_create()
4 {
5 stack s = (stack)malloc(sizeof(Lstack));
6 if (!s)
7 {
8 printf("申请失败\n");
9 return NULL;
10 }
11 s->p = (Node*)malloc(sizeof(Node));
12 if (!s->p)
13 {
14 printf("结点申请失败\n");
15 return NULL;
16 }
17 s->p->len = 0;
18 s->p->next = NULL;
19 printf("申请成功\n");
20 return s;
21 }
22 //判空
23 int stack_empty(stack s)
24 {
25 if (!s)
26 {
27 printf("未创建\n");
28 return -1;
29 }
30 return s->p->next == NULL;
31 }
32 //申请结点
33 Node *node_buy(datatype data)
34 {
35 Node * node = (Node*)malloc(sizeof(Node));
36 if (!node)
37 {
38 printf("结点申请失败\n");
39 return NULL;
40 }
41 node->data = data;
42 node->next = NULL;
43 return node;
44 }
45 //入栈
46 int push(stack s,datatype data)
47 {
48 if (!s)
49 {
50 printf("未创建\n");
51 return -1;
52 }
53 Node *node = node_buy(data);
54 node->next = s->p->next;
55 s->p->next = node;
56 s->p->len++;
57 printf("入栈成功\n");
58 return 1;
59 }
60 //出栈
61 int pop(stack s)
62 {
63 if (stack_empty(s))
64 {
65 printf("表空\n");
66 return -1;
67 }
68 Node *node = s->p->next;
69 s->p->next = s->p->next->next;
70 printf("出栈元素为:%d\n",node->data);
71 free(node);
72 node = NULL;
73 s->p->len--;
74 return 1;
75 }
76 //遍历栈
77 void stack_show(stack s)
78 {
79 if (stack_empty(s))
80 {
81 printf("表空\n");
82 return;
83 }
84 Node *node = s->p->next;
85 while (node != NULL)
86 {
87 printf("%d ",node->data);
88 node = node->next;
89 }
90 printf("遍历完成\n");
91 }
92 //销毁栈
93 stack stack_delete(stack s)
94 {
95 if (stack_empty(s))
96 {
97 free(s->p);
98 free(s);
99 }
100 else
101 {
102 Node *node = s->p,*q;
103 while (node)
104 {
105 q=node;
106 node = node->next;
107 free(q);
108 }
109 free(s);
110 }
111 s=NULL;
112 return s;
113 }
主函数:
1 #include"link_stack.h"
2
3 int main(int argc, const char *argv[])
4 {
5 stack s = stack_create();
6 if (!s)
7 {
8 printf("创建成功\n");
9 return -1;
10 }
11
12 push(s,1);
13 push(s,2);
14 push(s,3);
15 push(s,4);
16 push(s,5);
17 stack_show(s);
18
19 pop(s);
20 pop(s);
21 pop(s);
22 pop(s);
23 pop(s);
24
25 push(s,5);
26 s = stack_delete(s);
27 if (!s)
28 printf("销毁成功\n");
29 else
30 printf("销毁失败\n");
31 return 0;
32 }