栈操作

时间:2020-03-26
本文章向大家介绍栈操作,主要包括栈操作使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
 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 }

原文地址:https://www.cnblogs.com/sqdtss/p/12575078.html