c语言堆栈pop和push
时间: 2024-02-14 07:04:10 浏览: 26
在C语言中,堆栈是一种数据结构,常用的操作有push和pop。
push操作:将一个元素插入堆栈的顶部,即将元素放在堆栈的栈顶位置。
pop操作:将堆栈顶部的元素弹出,即删除栈顶元素。
下面是一个简单的C语言堆栈实现,包括push和pop操作:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
int stack[MAX_SIZE];
int top = -1;
void push(int x) {
if (top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
top++;
stack[top] = x;
}
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
int x = stack[top];
top--;
return x;
}
int main() {
push(1);
push(2);
push(3);
printf("%d\n", pop()); // 输出3
printf("%d\n", pop()); // 输出2
push(4);
printf("%d\n", pop()); // 输出4
printf("%d\n", pop()); // 输出1
printf("%d\n", pop()); // 输出Stack Underflow
return 0;
}
```
在这个例子中,我们使用数组来实现堆栈。当栈满时进行push操作,会输出“Stack Overflow”,当栈为空时进行pop操作,会输出“Stack Underflow”。