1 两栈实现一队列---s2实现出队
思路: 入队时,直接压入stack1中
出队时,判断stack2是否为空,如果stack2为空,则将stack1中的元素转移到stack2中,then再将stack2的栈顶元死弹出;
如果stack2不为空,直接弹出stack2中的元素
s.pash() s.top() s.pop()
//入队操作
void Enqueue( stack<int> &s1, stack<int> &s2, int m)
{
s1.push(m);
}
//出队操作
void Dequeue( stack<int> &s1, stack<int> &s2, &int m)
{
if(s2.empty())
{
int len = s1.size();
for(int i=0; i<len; i++)
{
s2.push(s1.top());
s2.pop();
}
}
m = s2.top()
s2.pop();
}
2 两个队列实现一个栈---q1实现出栈
思路:将queue1用来做进栈 &出栈操作 queue2作为中转战
入栈时, 直接压入queue1中
出栈时,先将queue1中除去最后一个元素外的元素依次出队列,并压入队列queue2中,将留在queue1中的最后一个元素出队列(即出队列元素),最后把queue2中的元素再次压入queue1中。
//进栈操作
void stackpush( queue<int> &q1, queue<int> &q2, int m)
{
q1.push(m);
}
//出栈操作
void stackpop( queue<int> &q1, queue<int> &q2, int &m)
{
int len1=q1.size();
for(int i=0;i<len1-1; i++)
{
q2.push(q1.front());
q1.pop();
}
m = q1.front();
q1.pop();
int len2=q2.size();
for(int j=0;j<len2;j++)
{
q1.push(q2.front());
q2.pop();
}
}