C语言实现顺序栈的入栈、出栈、栈元素读取操作
1 #include <stdio.h>
2 #include <stdlib.h>
3 #define MaxSize 20
4 #define MaxNum 10
5 #define ElemType int
6 typedef struct SqStack
7 { //存储结构定义
8 ElemType elem[MaxSize]; //栈元素的存储空间
9 int top; //栈顶指针
10 }SqStack; //存储结构类型名
11
12 void Init_SqStack(SqStack *s)
13 {
14 s->top = -1;
15 }
16
17 void Push(SqStack *s,ElemType x)
18 {
19 if (s->top < MaxSize - 1)
20 {
21 s->top = s->top + 1;
22 s->elem[s->top] = x;
23 }
24 else
25 printf("栈已满,不能入栈!\n");
26 }
27
28 int Pop(SqStack *s)
29 {
30 ElemType x;
31 if (s->top != -1)
32 {
33 x = s->elem[s->top];
34 s->top = s->top-1;
35 return x;
36 }
37 else
38 {
39 printf("栈为空,不能出栈!\n");
40 return 0;
41 }
42 }
43
44 int Get_Top(SqStack *s,ElemType x)
45 {
46 if (s->top != -1)
47 {
48 x = s->elem[s->top];
49 }
50 else
51 {
52 printf("栈为空!\n");
53 return 0;
54 }
55 }
56
57 int Get_Base(SqStack *s,ElemType x)
58 {
59 if (s->top != -1)
60 {
61 x = s->elem[0];
62 }
63 else
64 {
65 printf("栈为空!\n");
66 return 0;
67 }
68 }
69
70 void Display00_SqStack(SqStack *s)
71 {
72 int n;
73 if (s->top == -1)
74 printf("顺序栈为空");
75 else
76 {
77 for (n = 0; n <= s->top; n ++)
78 printf("%d ",s->elem[n]);
79 printf("\n");
80 }
81 }
82
83 void Display01_SqStack(SqStack *s)
84 {
85 int m;
86 if (s->top == -1)
87 printf("顺序栈为空!\n");
88 else
89 {
90 for (m = s->top; m >= 0; m--)
91 printf("%d ",s->elem[m]);
92 printf("\n");
93 }
94 }
95
96 int main()
97 {
98 SqStack s;
99 int x,y,cord,p;
100 ElemType a;
101 Init_SqStack(&s);
102 for (int t = 1; t <= MaxNum; t++)
103 {
104 Push(&s,t);
105 }
106 printf("初始化\n依次进栈元素为:\n");
107 Display00_SqStack(&s);
108 printf("从栈顶到栈底元素为: \n");
109 Display01_SqStack(&s);
110 do{
111 printf("\n 主菜单 \n");
112 printf(" 1 入栈 \n");
113 printf(" 2 出栈 \n");
114 printf(" 3 读栈顶元素 \n");
115 printf(" 4 读栈底元素 \n");
116 printf(" 5 结束程序 \n");
117 printf("-----------------------------------------------------\n");
118 printf("请输入你选择的菜单号<1,2,3,4>: ");
119 scanf("%d",&cord);
120 switch(cord)
121 {
122 case 1:
123 printf("请输入入栈元素:");
124 scanf("%d",&a);
125 Push(&s,a);
126 printf("由栈顶到栈底的元素为: \n");
127 Display01_SqStack(&s);
128 break;
129 case 2:
130 x = Pop(&s);
131 printf("出栈元素为: %d\n",x);
132 printf("由栈顶到栈底的元素为: \n");
133 Display01_SqStack(&s);
134 break;
135 case 3:
136 y = Get_Top(&s,x);
137 printf("栈顶元素为: %d\n",y);
138 printf("由栈顶到栈底的元素为: \n");
139 Display01_SqStack(&s);
140 break;
141 case 4:
142 p = Get_Base(&s,x);
143 printf("栈底元素为: %d\n",p);
144 printf("由栈顶到栈底的元素为: \n");
145 Display01_SqStack(&s);
146 break;
147 case 5:
148 exit(0);
149 break;
150 default:
151 printf("输入有误!");
152 }
153 }
154 while(cord <= 4);
155 }
运行结果:






来源:https://www.cnblogs.com/lixiansheng/p/7695111.html