设置两个栈,初始化之后,其中第一个栈通过调用多次入栈函数,完成第一个栈内容输入。c++
时间: 2024-05-19 12:12:31 浏览: 7
#include <stdio.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
int push(Stack *s, int x) {
if (s->top == MAXSIZE - 1) {
printf("Stack is full.\n");
return 0;
}
s->top++;
s->data[s->top] = x;
return 1;
}
int pop(Stack *s) {
if (s->top == -1) {
printf("Stack is empty.\n");
return 0;
}
int x = s->data[s->top];
s->top--;
return x;
}
int main() {
Stack s1, s2;
init(&s1);
init(&s2);
// 输入第一个栈的内容
int x;
do {
printf("Enter a number (-1 to stop): ");
scanf("%d", &x);
if (x != -1)
push(&s1, x);
} while (x != -1);
// 将第一个栈的内容倒序压入第二个栈
while (s1.top != -1) {
int x = pop(&s1);
push(&s2, x);
}
// 输出第二个栈的内容
printf("Second stack: ");
while (s2.top != -1) {
int x = pop(&s2);
printf("%d ", x);
}
printf("\n");
return 0;
}
相关推荐
![](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)