设已知有两个堆栈S1和S2,请用这两个堆栈模拟出一个队列Q。
所谓用堆栈模拟队列,实际上就是通过调用堆栈的下列操作函数:
int IsFull(Stack S)
:判断堆栈S是否已满,返回1或0;
int IsEmpty (Stack S )
:判断堆栈S是否为空,返回1或0;
void Push(Stack S, ElementType item )
:将元素item压入堆栈S;
ElementType Pop(Stack S )
:删除并返回S的栈顶元素。
实现队列的操作,即入队void AddQ(ElementType item)
和出队ElementType DeleteQ()
。
输入格式:
输入首先给出两个正整数N1和N2,表示堆栈S1和S2的最大容量。随后给出一系列的队列操作:A item表示将item入列(这里假设item为整型数字);D表示出队操作;T表示输入结束。
输出格式:
对输入中的每个D操作,输出相应出队的数字,或者错误信息ERROR:Empty
。如果入队操作无法执行,也需要输出ERROR:Full
。每个输出占1行。
输入样例:
3 2
A 1 A 2 A 3 A 4 A 5 D A 6 D A 7 D A 8 D D D D T
输出样例:
ERROR:Full
1
ERROR:Full
2
3
4
7
8
ERROR:Empty
用一个堆栈stack1负责入队,一个堆栈stack2负责出队。
本题要将容量小的堆栈用于stack1(入队的堆栈),否则得不到指定的输出.
要入队时,如果stack1已满,则看stack2是否为空:stack2为空则先把stack1的元素全部压入stack2,再把待入队元素压入stack1,不为空就输出ERROR:Full
。
出队时,如果stack2为空,则看一下stack1是否有数据,有的话就先把stack1的数据拿过来再出队,否则就输出ERROR:Empty
。
#include <stdio.h>
#include <stdlib.h>
typedef struct stack {
int *data;
int top;
int size;
} * Stack;
Stack creatStack(int size) {
Stack stack = (Stack)malloc(sizeof(struct stack));
stack->top = -1;
stack->size = size;
stack->data = (int *)malloc(sizeof(int) * size);
return stack;
}
int isEmpty(Stack stack) {
return stack->top == -1;
}
int isFull(Stack stack) {
return stack->top == stack->size - 1;
}
int push(Stack stack, int data) {
if (isFull(stack))
return 0;
stack->data[++stack->top] = data;
return 1;
}
int pop(Stack stack) {
if (isEmpty(stack))
return 0;
return stack->data[stack->top--];
}
// 返回值是1或0
// 我理解错了,如果stack2非空,无法从stack1压入stack2的!!!
int addQ(Stack stack1, Stack stack2, int data) {
if (!push(stack1, data)) {
// 错误:入栈1失败,说明栈1满,接下来判断是否可以把栈1的元素压入栈2
// if (stack2->size - 1 - stack2->top >= stack1->size)
if (isEmpty(stack2)) {
while (!isEmpty(stack1)) {
push(stack2, pop(stack1));
}
push(stack1, data);
} else {
return 0;
}
}
return 1;
}
// 是否可以出队还需另外判断,只出队。
int deleteQ(Stack stack2) {
return pop(stack2);
}
void swap(int *x, int *y) {
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
// 入队时stack1满就压入stack2,出队时stack2空也要压入。
// 在这题,从stack1压入stack2应该是一次全部压入,不能压入一部分
int main() {
int size1, size2;
scanf("%d%d", &size1, &size2);
if (size1 > size2)
swap(&size1, &size2);
Stack stack1, stack2;
stack1 = creatStack(size1);
stack2 = creatStack(size2);
getchar();
char operation;
scanf("%c", &operation);
while (operation != 'T') {
// 缓冲一下输入的空格
getchar();
if (operation == 'A') {
int data;
scanf("%d", &data);
getchar();
if (!addQ(stack1, stack2, data))
printf("ERROR:Full\n");
} else if (operation == 'D') {
// 栈2空的话从栈1进货
if (isEmpty(stack2)) {
if (isEmpty(stack1))
printf("ERROR:Empty\n");
else {
while (!isEmpty(stack1))
push(stack2, pop(stack1));
}
}
if (!isEmpty(stack1) || !isEmpty(stack2))
printf("%d\n", pop(stack2));
// if (deleteQ(stack2) != 0)
// printf("%d\n", deleteQ(stack2));
}
scanf("%c", &operation);
}
return 0;
}