c语言:现有一个空栈ss,按顺序执行nn个操作序列,每个操作是下面的两种之一: 1. 往ss中压入一个正整数kk 2.弹出ss的栈顶元素,同时将其输出
时间: 2024-03-23 17:38:10 浏览: 62
可以使用数组模拟栈的操作,具体代码如下:
```c
#include <stdio.h>
#define MAXSIZE 100
int stack[MAXSIZE]; // 定义栈
int top = -1; // 标记栈顶
// 判断栈是否为空
int isEmpty() {
return top == -1;
}
// 判断栈是否已满
int isFull() {
return top == MAXSIZE - 1;
}
// 入栈操作
void push(int k) {
if (isFull()) {
printf("栈已满,无法入栈。\n");
return;
}
stack[++top] = k;
}
// 出栈操作
int pop() {
if (isEmpty()) {
printf("栈已空,无法出栈。\n");
return -1;
}
int num = stack[top--];
printf("%d ", num);
return num;
}
int main() {
int n, op, k;
printf("请输入操作序列的长度:");
scanf("%d", &n);
printf("请输入操作序列:\n");
// 依次执行操作序列
for (int i = 0; i < n; i++) {
scanf("%d", &op);
if (op == 1) {
scanf("%d", &k);
push(k); // 执行入栈操作
} else if (op == 2) {
pop(); // 执行出栈操作
} else {
printf("无效操作!\n");
}
}
return 0;
}
```
上述代码中,首先定义了一个数组作为栈,并定义了栈顶指针top,初始值为-1,表示栈为空。然后定义了isEmpty()和isFull()函数分别用于判断栈是否为空和已满,push()函数用于将元素入栈,pop()函数用于将栈顶元素出栈并输出。在主函数中,首先输入操作序列的长度n,然后依次输入n个操作,并根据操作类型执行相应的函数。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)