数据结构-C语言实现-动态顺序存储栈
标签:play 整数 div 扩容 items case 存储 include code
1 #include 2 #include 3 #include 4 #include string.h>
5 typedef int ElemType;
6 typedef struct stack{
7 ElemType *items;
8 ElemType top;
9 }stack;
10 stack * initstack(){
11 stack * stacks=(stack *)malloc(sizeof(stack));
12 stacks->items=(ElemType *)malloc(sizeof(ElemType)*10);//动态分配大小为10,后续扩容可继使用realloc分配
13 stacks->top=-1;//栈顶初始化为-1
14 return stacks;
15 }
16 void pop(stack * stacks){
17 if(stacks->top>=0){
18 printf("弹出的数:%d\n",stacks->items[stacks->top]);
19 stacks->top--;
20 }
21 else
22 printf("栈已空!\n");
23 }
24 void push(stack * stacks){
25 printf("输入你想添加的整数:\n");
26 ElemType a;
27 scanf("%d",&a);
28 stacks->items[stacks->top+1]=a;
29 stacks->top++;
30 }
31 void display(stack * stacks){
32 int a=0;
33 if(stacks->top>=0){
34 while(atop){
35 printf("第%d个数:%d\n",a+1,stacks->items[a]);
36 a++;
37 }
38 }
39 else
40 printf("栈为空!\n");
41 }
42 void menu(){
43 printf("键入以下选项以操作,ctrl+z退出\nA:添加数据\nB:弹出数据\nC:打印数据\n");
44 }
45 void main(){
46 stack *stacks=initstack();
47 menu();
48 char ch;
49 printf("%d\n",stacks->top);
50 while((ch=getchar())!=EOF){
51 setbuf(stdin,NULL);
52 switch (toupper(ch)){
53 case ‘A‘: push(stacks);break;
54 case ‘B‘: pop(stacks);break;
55 case ‘C‘: display(stacks);break;
56 }
57 menu();
58 setbuf(stdin,NULL);
59 }
60 }
数据结构-C语言实现-动态顺序存储栈
标签:play 整数 div 扩容 items case 存储 include code
原文地址:https://www.cnblogs.com/Let-us-Coding/p/12936129.html
评论