这题刚看到的时候一脸懵逼,明明有好好的队列不用,偏要用两个栈模拟队列
但既然题目这么要求了那就只能这样写呗
梳理一下模拟的思路:
思路:
堆栈后进先出,队列先进先出
那堆栈来回两次不就先进先出吗
但是要注意的是,当要求输出是,如果第二个堆栈是空的时才把前一个堆栈的数据压入栈
否则就对第二个栈直接输出
但是!!
如果第一个堆栈容量为3,第二个为2
当第一个堆栈满了
3
2
1
要求出队
那么第一个堆栈的数压入第二个栈
2
3
还有个1,如果就对此出队明显不合法
所以应该取大容量的为第二堆栈
原因:如果大的空间给入栈数组,当要输出时得把入站数组里面的数据都压到出栈数据里,这是会造成数据溢出
接下来的模拟原理大概如图
代码实现的几种讨论说一下把
入栈:
- 如果栈一未满,直接入栈
- 如果栈一满了,但是栈二空的,把栈一数据压入栈二,再将新的数据入栈一
- 如果栈一满了,栈二有数据,那么此时就不能入栈,一旦入栈这里就不能实现队列的顺序了,为什么是栈二有数据就不能入新数据呢,自己举个例子试试就知道了
出栈:
- 栈二不空,直接出栈
- 栈二无数据,但栈一有,转栈一数据到栈二再出栈二
- 栈二栈一都无数据,不用出了
关于入栈
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
#define ERROR -1000000
typedef int ElementType;
typedef struct stack* Stack;
struct stack
{
ElementType *Data;
int MaxSize;
int Top;
};
bool IsFull(Stack S);// 判断堆栈S是否已满,返回1或0;
bool IsEmpty(Stack S);//判断堆栈S是否为空,返回1或0;
void Push(Stack S, ElementType item);// 将元素item压入堆栈S;
ElementType Pop(Stack S);// 删除并返回S的栈顶元素。
Stack CreatStack(int n);//初始化栈
int main()
{
int N1, N2;
cin >> N1 >> N2;//S1和S2的最大容量
if (N1 > N2) swap(N1, N2);//第二个栈空间大
Stack S1 = CreatStack(N1);
Stack S2 = CreatStack(N2);//空间较大的那个
char c;
while (1)
{
cin >> c;
if (c == 'T') break;
switch (c) {
case 'A'://入栈
ElementType item;
cin >> item;
if (IsFull(S1) && !IsEmpty(S2)) {
//当一栈满了并且二栈不空时不能入栈,不然就破坏了队列的顺序
cout << "ERROR:Full" << endl;
}
else if (IsFull(S1) && IsEmpty(S2))
{
//如果一栈满了但是二栈空着,就把一栈的所有数据转移到二栈
while (!IsEmpty(S1))
{
ElementType temp = Pop(S1);
Push(S2,temp);
}
Push(S1, item);//再把新的数据推入一栈
}
else Push(S1, item);//否则直接入一栈
break;
case'D':
if (IsEmpty(S1) && IsEmpty(S2)) {//两个栈都空,没数据给你出栈
cout << "ERROR:Empty" << endl;
}
else if (!IsEmpty(S2))//二栈不空,直接出栈
{
ElementType temp = Pop(S2);
cout << temp << endl;
}
else//二栈空,但是一栈有数据就直接把栈一的数据移到栈二就好
//如果此时栈一未满也要入二栈,这样才能保住队列的顺序
{
while (!IsEmpty(S1))
{
ElementType temp = Pop(S1);
Push(S2, temp);
}//把一栈全推到二栈
cout << Pop(S2) << endl;//转移完以后别忘了再次出栈
}
break;
}
}
return 0;
}
void Push(Stack S, ElementType item)
{
S->Top++;
S->Data[S->Top] = item;
}
ElementType Pop(Stack S)
{
ElementType temp = S->Data[S->Top];
S->Top--;
return temp;
}
Stack CreatStack(int n)
{
Stack S = (Stack)malloc(sizeof(struct stack));//c++别用malloc,可能会有兼容性问题
S->Data = (ElementType*)malloc(sizeof(ElementType) * n);
S->Top = -1;
S->MaxSize = n;
return S;
}
bool IsFull(Stack S)
{
if (S->Top == S->MaxSize-1) return true;//满了
else return false;
}
bool IsEmpty(Stack S)
{
if (S->Top == -1) return true;//空的
else return false;
}