设置两个栈,初始化之后,其中第一个栈通过调用多次入栈函数,完成第一个栈内容输入。c语言+
时间: 2024-06-01 10:09:35 浏览: 14
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100 // 定义栈的最大容量
typedef struct {
int data[MAXSIZE];
int top;
} Stack;
// 初始化栈
void init(Stack *s) {
s->top = -1;
}
// 判断栈是否为空
int isEmpty(Stack *s) {
return s->top == -1;
}
// 判断栈是否已满
int isFull(Stack *s) {
return s->top == MAXSIZE - 1;
}
// 入栈
void push(Stack *s, int x) {
if (isFull(s)) {
printf("Stack is full.\n");
return;
}
s->data[++s->top] = x;
}
// 出栈
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
return -1;
}
return s->data[s->top--];
}
int main() {
Stack s1, s2;
int x;
// 初始化栈
init(&s1);
init(&s2);
// 输入第一个栈的内容
printf("Please input the elements of the first stack (input -1 to end):\n");
scanf("%d", &x);
while (x != -1) {
push(&s1, x);
scanf("%d", &x);
}
// 输出第一个栈的内容
printf("The elements of the first stack are:\n");
while (!isEmpty(&s1)) {
x = pop(&s1);
printf("%d ", x);
push(&s2, x); // 同时将元素压入第二个栈
}
printf("\n");
// 输出第二个栈的内容
printf("The elements of the second stack are:\n");
while (!isEmpty(&s2)) {
x = pop(&s2);
printf("%d ", x);
}
printf("\n");
return 0;
}