已知一个双向堆栈stackM,c语言编程实现:从键盘输入一个数据,若输入的是奇数,则存入左栈;若输入的是偶数,则存入右栈,直到栈蛮为止
时间: 2024-02-22 07:58:46 浏览: 31
以下是C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top1; // 左栈顶指针
int top2; // 右栈顶指针
} Stack;
void initStack(Stack *s) {
s->top1 = -1; // 左栈初始化为空
s->top2 = MAX_SIZE; // 右栈初始化为空
}
int isFull(Stack *s) {
return s->top1 == s->top2 - 1; // 栈满条件
}
int isEmpty1(Stack *s) {
return s->top1 == -1; // 左栈空条件
}
int isEmpty2(Stack *s) {
return s->top2 == MAX_SIZE; // 右栈空条件
}
void push1(Stack *s, int x) {
if (isFull(s)) {
printf("Stack is full.\n");
return;
}
s->top1++;
s->data[s->top1] = x;
}
void push2(Stack *s, int x) {
if (isFull(s)) {
printf("Stack is full.\n");
return;
}
s->top2--;
s->data[s->top2] = x;
}
int pop1(Stack *s) {
if (isEmpty1(s)) {
printf("Stack is empty.\n");
return -1;
}
int x = s->data[s->top1];
s->top1--;
return x;
}
int pop2(Stack *s) {
if (isEmpty2(s)) {
printf("Stack is empty.\n");
return -1;
}
int x = s->data[s->top2];
s->top2++;
return x;
}
int main() {
Stack stackM;
initStack(&stackM);
int num;
printf("Please input numbers, and enter 0 to end:\n");
scanf("%d", &num);
while (num != 0) {
if (num % 2 == 1) { // 奇数入左栈
push1(&stackM, num);
} else { // 偶数入右栈
push2(&stackM, num);
}
scanf("%d", &num);
}
printf("Left stack:\n");
while (!isEmpty1(&stackM)) {
printf("%d ", pop1(&stackM)); // 逆序输出左栈元素
}
printf("\n");
printf("Right stack:\n");
while (!isEmpty2(&stackM)) {
printf("%d ", pop2(&stackM)); // 顺序输出右栈元素
}
printf("\n");
return 0;
}
```
这个程序会接收输入的数字,如果是奇数就存入左栈,如果是偶数就存入右栈,直到输入0为止。最后分别逆序输出左栈和顺序输出右栈的元素。