今天遇到一道习题:
使用两个栈s1和s2模拟实现队列的功能。
在此基础上,试写了使用一个共享栈进行一个队列的模拟。
基本的设计思路如下:
入队:
首先判断“队列”是否为满。判断标志为左右栈顶指针差1。
队列的入队操作由左栈入栈模拟完成。
出队:
首先判断“队列”是否非空。判断标志为左右栈均空。
当出队时,总体思路是可以通过先将左栈元素出栈,再将该元素入右栈,最后该元素在右栈出栈来模拟实现。
会出现如下两种情况:
1. 当右栈非空时,由于右栈的出栈序列与左栈入栈序列相同,则正好实现队列的“先进先出”,则直接对右栈进行出栈操作即可得到出队序列;
2.当右栈为空时,将左栈所有元素依次出栈并入右栈,并执行右栈的出栈操作。
C++代码如下:
#define MaxSize 50;
using namespace std;
struct Stack //定义共享栈
{
int s[MaxSize];
int ltop=-1,rtop=MaxSize;
};
//定义共享栈的出入栈操作
bool pushLStack(Stack &st,int x) //左栈的入栈操作
{
if(st.ltop+1==st.rtop) //判断共享栈是否已满
return false;
else
{
st.s[++st.ltop]=x;
return true;
}
}
bool pushRStack(Stack &st,int x) //右栈的入栈操作
{
if(st.ltop+1==st.rtop) //判断共享栈是否已满
return false;
else
{
st.s[--st.rtop]=x;
return true;
}
}
bool popLStack(Stack &st,int &x) //左栈的出栈操作
{
if(st.ltop==-1) //判断左栈是否为空
return false;
else
{
x=st.s[st.ltop--];
return true;
}
}
bool popRStack(Stack &st,int &x) //右栈的出栈操作
{
if(st.rtop==MaxSize) //判断右栈是否为空
return false;
else
{
x=st.s[st.ltop++];
return true;
}
}
//用共享栈模拟队列
bool queueEmpty(Stack st) //判断队列是否为空
{
if(st.ltop==-1&&st.rtop==MaxSize)
return true;
else
return false;
}
bool enQueue(Stack &st,int x) //入队操作
{
if(st.ltop+1==st.rtop
return false;
else
pushLStack(st,x); //若队列不满,将元素入左栈
}
bool deQueue(Stack &st,int &x) //出队操作
{
if(queueEmpty()) //若队列非空,进行出队操作
return false;
else
{
if(st.rtop!=MaxSize) //判断右栈是否非空,若右栈非空,将右栈进行出栈
{
popRStack(st,&x);
return te;
}
else
{
int change;
while(st.ltop!=-1) //若右栈为空,将左栈依次出栈并依次入右栈
{
popLStack(st,&change);
pushRStack(st,change);
}
popRStack(st,&x); //执行右栈的出栈操作
return true;
}
}
}
若只单纯使用两个栈来进行模拟,操作略有差别,相对容易实现一点,基本思路是一样的。