用递归颠倒一个栈。例如输入栈{1, 2, 3, 4, 5},1在栈顶。 颠倒之后的栈为{5, 4, 3, 2, 1},5处在栈顶。用C语言写
时间: 2024-05-13 21:21:11 浏览: 8
下面是用C语言实现递归颠倒一个栈的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
void push(int item) {
if (top >= MAX_SIZE - 1) {
printf("Stack overflow!\n");
exit(1);
}
stack[++top] = item;
}
int pop() {
if (top < 0) {
printf("Stack underflow!\n");
exit(1);
}
return stack[top--];
}
int is_empty() {
return top < 0;
}
void display() {
printf("[");
for (int i = top; i >= 0; i--) {
printf("%d ", stack[i]);
}
printf("]\n");
}
void insert_at_bottom(int x) {
if (is_empty()) {
push(x);
} else {
int item = pop();
insert_at_bottom(x);
push(item);
}
}
void reverse() {
if (!is_empty()) {
int item = pop();
reverse();
insert_at_bottom(item);
}
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter %d elements to push onto the stack: ", n);
for (int i = 0; i < n; i++) {
int item;
scanf("%d", &item);
push(item);
}
printf("Before reversal: ");
display();
reverse();
printf("After reversal: ");
display();
return 0;
}
```
实现的思路是先将栈原来的元素逐个弹出,然后再递归地将它们插入到栈的底部,这样就达到了颠倒的效果。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)