即两个栈,stack1用来push数据,即{a,b,c},然后把stack1的数据pop出来,由于栈是先进后出原则,所以出来顺序是{c,b,a}
然后在stack2 push stack1 所弹出来的数据,存储即为{c,b,a},pop的话就是{a,b,c},即满足了队列的先进先出原则。
class Solution
{
public:
void push(int node)
{
stack1.push(node);
}
int pop()
{
int head;
if(stack2.empty())
{
while( !stack1.empty())
{
head = stack1.top();
stack1.pop();
stack2.push(head); //实现入队操作
}
}
head = stack2.top();
stack2.pop();
return head; //实现出队操作
}
private:
stack<int> stack1;
stack<int> stack2;
};
引申:
如果是两个队列实现一个栈
思路:queue1 用作进栈出栈,queue2作为一个中转
入栈时,直接压入queue1中
出栈时,先将queue1的元素除最后一个元素以外依次出队,并压入队列queue2中
留在queue1中的最后一个元素出队列即为出栈元素
最后再把queue2中的元素再次压入queue1中
基本步骤:
图(1)若是栈插入元素,则先进后出,插入元素abcd时,应d先出去
图(2)把q1的除了d以外的元素(abc)全部出队,压入队列q2中,pop “d”,即完成栈顶元素的出栈
图(3)把q2中的除了c以外的元素(ab)全部出队,压入队列q1中,pop“c”,即完成出栈
图(4)同理,pop“b”
图(5)对于新入队的元素“e”,那么a不能删除,此时我们必须先将除了e以外的其他元素全部压入q2中,
pop“e”之后,才能对a进行操作。
class Mystack
{
public:
void push(int node)
{
queue1.push(node); //进栈
}
//出
int pop()
{
int head;
if( queue1.size() > 0)
{
while (queue1.size() > 1)
{
queue2.push(queue1.front()); //获取队头的元素然后然后push它
queue1.pop();
}
head = queue1.front();
queue1.pop();
}
else
{
while(queue2.size() > 1)
{
queue1.push(queue2.front());
queue2.pop();
}
head = queue2.front();
queue2.pop();
}
return head;
}
private:
queue<int> queue1;
queue<int> queue2;
};
int main()
{
Mystack ss;
ss.push(1);
ss.push(2);
ss.push(3);
cout << ss.pop() << endl;
cout << ss.pop() << endl;
cout << ss.pop() << endl;
}