什么是堆栈,用C语言举个例子
时间: 2023-08-19 22:03:46 浏览: 53
堆栈(stack)是一种数据结构,它的特点是先进后出(Last In First Out,LIFO)。堆栈通常具有 push(入栈) 和 pop(出栈) 两个基本操作。
下面是一个用C语言实现堆栈的例子:
```c
#include <stdio.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
bool isEmpty(Stack *s) {
return s->top == -1;
}
bool isFull(Stack *s) {
return s->top == MAXSIZE - 1;
}
void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack is full!\n");
return;
}
s->top++;
s->data[s->top] = value;
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty!\n");
return -1;
}
int value = s->data[s->top];
s->top--;
return value;
}
int main() {
Stack s;
init(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
while (!isEmpty(&s)) {
printf("%d ", pop(&s));
}
printf("\n");
return 0;
}
```
在这个例子中,我们使用结构体来定义一个堆栈,其中 `data` 数组用来存储堆栈中的元素,`top` 表示当前栈顶的位置。我们通过 `init` 函数来初始化堆栈,`isEmpty` 和 `isFull` 函数分别用来判断堆栈是否为空和是否已满,`push` 和 `pop` 函数用来入栈和出栈。在 `main` 函数中,我们创建一个堆栈对象并进行了一些入栈和出栈操作,并最终打印出堆栈中的元素。
相关推荐
![](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)