2023-03-30-栈的基本操作

发布时间 2023-03-30 20:37:58作者: 正方形的被子
 1 //栈stack
 2 
 3 
 4 #include <stdio.h>
 5 #include <stdbool.h>
 6 
 7 #define MAXSIZE 100
 8 
 9 typedef struct
10 {
11     int data[MAXSIZE]; //数据
12     int top;   //栈顶指针,初始为-1
13 }*SqStack;
14 
15 void initStack(SqStack S)//初始化栈
16 {
17     S->top=-1;//将栈顶指针设置为-1,所以每次top都指向最后一个元素在数组中的下标,而不是最后一个元素的下一个位置
18 }
19 
20 bool StackEmpty(SqStack S)//判断栈是否为空
21 {
22     if(S->top==-1)//判断栈顶指针是否为-1
23     {
24         return true;//如果是就返回true
25     }
26     else{
27         return false;
28     }
29 }
30 
31 bool Push(SqStack S,int value)//进栈
32 {
33     if(S->top==MAXSIZE-1)//top为0时即指向data[0],数组的最大长度为MAXSIZE-1,所以top也是
34     {
35         return false;
36     }
37     else{
38         S->top++;
39         S->data[S->top] = value;
40         return true;
41     }
42 }
43 
44 bool Pop(SqStack S,int *e)//出栈,并获取出栈元素的值
45 {
46     if(S->top==-1)
47     {
48         return false;
49     }
50     else{
51         *e=S->data[S->top];
52         S->top--;
53         return true;
54     }
55 }
56 
57 bool GetTop(SqStack S,int *e)//读栈顶元素
58 {
59     if(S->top==-1)
60     {
61         return false;
62     }
63     else
64     {
65         *e=S->data[S->top];//将栈顶元素传给e
66         return true;
67     }
68 }
69 
70 int main()
71 {
72     SqStack S;
73     initStack(S);
74     int x;
75     for(int i=0;i<5;i++)
76     {
77         scanf("%d",&x);
78         Push(S,x);
79     }
80     for(int j=0;j<=S->top;j++)
81     {
82         printf("%d ",S->data[j]);
83     }
84     int *e;
85     int a=0;
86     e=&a;//对指针进行初始化,避免出现野指针
87     GetTop(S,e);
88     printf("TOP: %d\n",*e);
89     Pop(S,e);
90     printf("Pop_value: %d \n",*e);
91     //以下为错误代码,为什么添加了下列代码之后程序就跑不起来了?
92     // for(int pp=0;pp<=(S->top);pp++)
93     // {
94     //     printf("%d",S->data[pp]);
95     // }
96     return 0;
97 }