题目
设已知有两个堆栈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
结尾无空行
思路
/*
一开始拿到题目,对于用双栈来模拟队列其实有点不理解,稍微模拟了才知道如何运用;
对于双栈s1, s2;栈s1模拟数据进队列,操作和元素进栈一样;因为栈是先进后出,队列是先进先出,如何将栈s1内的最底部元素第一个输出就很关键,这里就要运用到栈s2;(图示)
操作就是使用一次循环将s1内元素以出栈的顺序,再压入栈s2中;此时栈s2最先Pop的元素就是s1最底层的元素;
注意点:
1、根据题意模拟,栈s1的容量比s2要小
2、进队和入队的条件判断
*/
代码
#include <stdio.h>
#include <stdlib.h>
typedef struct SNode *stack;
struct SNode{
int *data;
int top;
int maxsize;
};
stack Creat(int maxsize)
{
stack s = (stack)malloc(sizeof(struct SNode));
s->data = (int *) malloc(maxsize * sizeof(int));
s->top = -1;
s->maxsize = maxsize;
return s;
}
int ISFull(stack s)
{
if(s->top == s->maxsize-1)
return 1;
else return 0;
}
int ISEmpty(stack s)
{
if(s->top == -1)
return 1;
else return 0;
}
void Push(stack s, int item)
{
s->data[++s->top] = item;
}
int Pop(stack s)
{
return s->data[s->top--];
}
int main()
{
int n1, n2;
scanf("%d %d", &n1, &n2);
getchar();
stack s1, s2;
if(n1 > n2)
{
s1 = Creat(n2);
s2 = Creat(n1);
}
else
{
s1 = Creat(n1);
s2 = Creat(n2);
}
char str;
while (scanf("%c", &str), str!='T')
{
if(str == 'A')
{
int x;
scanf("%d", &x);
if(!ISFull(s1)) //s1未满,进栈s1
Push(s1, x);
else if(ISFull(s1) && !ISEmpty(s2)) //s1栈满,s2也不为空,说明FULL
printf("ERROR:Full\n");
else if(ISFull(s1) && ISEmpty(s2)) //如果s1栈满,s2为空;先将s1内所有元素移动至s2内,再Push(s1, x)
{
while (!ISEmpty(s1)) Push(s2, Pop(s1));
Push(s1, x);
}
}
else if(str == 'D')
{
if(!ISEmpty(s2))
printf("%d\n", Pop(s2));
else if(ISEmpty(s1) && ISEmpty(s2))
printf("ERROR:Empty\n");
else if(!ISEmpty(s1) && ISEmpty(s2))
{
while (!ISEmpty(s1)) Push(s2, Pop(s1));
printf("%d\n", Pop(s2));
}
}
}
return 0;
}