如何用两个栈实现一个队列以及用两个队列实现一个栈

一、两个栈实现一个队列

设两个栈分别为stack1和stack2,stack1主要负责“进入”,模拟的是“队尾”;stack2主要负责“弹出”,模拟的是“队头”。具体思路如下:

1、对于“数据入队”操作,只需要将数据压入stack1即可

2、对于“数据出队”操作,若stack2非空,直接弹出栈顶元素;若stack2是空,将stack1中所有元素弹入stack2之后,弹出stack2栈顶元素

实现代码如下:

 1 class Solution
 2 {
 3 public:
 4     void push(int node) {
 5         stack1.push(node);
 6     }
 7  
 8     int pop() {
 9         int a;
10         if (stack2.empty())
11         {
12             while (!stack1.empty())
13             {
14                 a = stack1.top();
15                 stack1.pop();
16                 stack2.push(a);
17             }
18         }
19         a = stack2.top();
20         stack2.pop();
21         return a;
22     }
23  
24 private:
25     stack<int> stack1;
26     stack<int> stack2;
27 };
View Code

二、两个队列实现一个栈

设两个队列分别为queue1和queue2,用队列模拟栈需要注意——任何时候至少有一个队列要是空的,我们的插入操作所做的事情就是每次只往空的队列中插入数据,然后把另一个队列中的数据移到该队列,如此一来永远保持最后插入的元素在某个队列的“队头”,一旦有弹出操作,先弹出它,满足栈的“后进先出”原则,完成了两个队列对一个栈的模拟。

1、“插入操作”  将数据插入到空的队列中,然后把另一个队列中的元素全部移到该队列

2、“删除操作” 将非空队列的队头数据删除即可

3、“弹出操作” 弹出非空队列队首元素

4、“判空操作” 两个队列均为空才判空

代码如下:

 1 class Stack {
 2 public:
 3     // Push element x onto stack.
 4     void push(int x) {
 5         if (!q1.empty())
 6         {
 7             q2.push(x);
 8             while (!q1.empty())
 9             {
10                 q2.push(q1.front());
11                 q1.pop();
12             }
13         }
14         else
15         {
16             q1.push(x);
17             while (!q2.empty())
18             {
19                 q1.push(q2.front());
20                 q2.pop();
21             }
22         }
23     }
24 
25     // Removes the element on top of the stack.
26     void pop() {
27         if (q1.empty()&&q2.empty())
28             throw new exception("stack is empty");
29         else if (!q1.empty()) q1.pop();
30         else q2.pop();
31     }
32 
33     // Get the top element.
34     int top() {
35         if (!q1.empty()) return q1.front();
36         else return q2.front();
37     }
38 
39     // Return whether the stack is empty.
40     bool empty() {
41         return (q1.empty()&&q2.empty());
42     }
43 
44 private:
45     queue<int> q1, q2;
46 };
View Code
原文地址:https://www.cnblogs.com/dapeng-bupt/p/7562743.html