思路:
栈——LIFO(后进先出);队列——FIFO(先进先出)。
用两个栈实现队列的根本点是要保证最先进来的(最老的)元素出栈时处于栈顶位置。
使用栈1来入栈,栈2来出栈。具体流程如下:
1. 入栈操作:用栈1入栈,直接push到栈1顶部;(元素全部在栈1,栈2为空)
2. 出栈操作:先将栈1中的元素依次拿出,入栈到栈2中。完成后,原来最先进入栈1的(最老的)元素会在栈2的栈顶,最后进入栈1(最新的)元素会在栈底。
此时,执行栈2的pop,将最老的元素出栈。出栈操作完成。此时,还需要把栈2的元素依次再拿出,push回栈1。
1 class Solution 2 { 3 public: 4 //入栈 5 void push(int node) { 6 stack1.push(node); 7 } 8 //出栈 9 int pop() { 10 int top; 11 //将栈1中的内容全部压到栈2中 12 while(!stack1.empty()) 13 { 14 stack2.push(stack1.top()); 15 stack1.pop(); 16 } 17 //将栈2的栈顶出栈 18 top=stack2.top(); 19 stack2.pop(); 20 //将栈2中剩下的内容再放回栈1中 21 while(!stack2.empty()) 22 { 23 stack1.push(stack2.top()); 24 stack2.pop(); 25 } 26 return top; 27 } 28 private: 29 stack<int> stack1; 30 stack<int> stack2; 31 };
原文:https://www.cnblogs.com/smartheadliu/p/12774119.html