用C++实现栈这一数据结构
时间: 2024-05-12 12:18:55 浏览: 24
以下是用C实现栈的代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
void push(Stack *s, int x) {
if (s->top == MAX_SIZE - 1) {
printf("Stack is full\n");
return;
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (s->top == -1) {
printf("Stack is empty\n");
return -1;
}
return s->data[s->top--];
}
int main() {
Stack s;
s.top = -1;
push(&s, 1);
push(&s, 2);
push(&s, 3);
printf("%d\n", pop(&s));
printf("%d\n", pop(&s));
printf("%d\n", pop(&s));
printf("%d\n", pop(&s));
return 0;
}
```
这里使用了结构体来定义栈,其中data数组存储栈中的元素,top指向栈顶元素。push函数用于向栈中添加元素,pop函数用于从栈中弹出元素,当栈为空或者已满时会进行错误提示。在main函数中,我们首先创建了一个空栈,然后向栈中添加了三个元素,接着依次弹出这三个元素,最后尝试弹出一个空栈,此时会提示栈为空。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)