Implement the following operations of a stack using queues. (Easy)
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- empty() -- Return whether the stack is empty.
Notes:
- You must use only standard operations of a queue -- which means only
push to back
,peek/pop from front
,size
, andis empty
operations are valid. - Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
- You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
分析:
使用两个队列实现,其中一个队列为空,用来进行颠倒顺序和输出队尾元素。
入栈操作: 向非空队列内入队即可
出栈操作:将非空队列除队尾元素外的所有元素导入另一个空队列,剩余队尾元素即为待应该待出栈元素
top()操作: 同出栈,注意只需访问返回,不需要让其出队,即仍需将其导入另一队列
注意:两队列地位平等,均可能用作储存和转移工作
代码:
1 class Stack { 2 private: 3 queue<int> q1,q2; 4 public: 5 // Push element x onto stack. 6 void push(int x) { 7 if(!q1.empty()){ 8 q1.push(x); 9 } 10 else{ 11 q2.push(x); 12 } 13 } 14 15 // Removes the element on top of the stack. 16 void pop() { 17 if(!q1.empty()){ 18 while(q1.size() > 1){ 19 q2.push(q1.front()); 20 q1.pop(); 21 } 22 q1.pop(); 23 }else{ 24 while(q2.size() > 1){ 25 q1.push(q2.front()); 26 q2.pop(); 27 } 28 q2.pop(); 29 } 30 } 31 32 // Get the top element. 33 int top() { 34 if(!q1.empty()){ 35 while(q1.size() > 1){ 36 q2.push(q1.front()); 37 q1.pop(); 38 } 39 int ans = q1.front(); 40 q2.push(q1.front()); 41 q1.pop(); 42 return ans; 43 }else{ 44 while(q2.size() > 1){ 45 q1.push(q2.front()); 46 q2.pop(); 47 } 48 int ans = q2.front(); 49 q1.push(q2.front()); 50 q2.pop(); 51 return ans; 52 } 53 } 54 55 // Return whether the stack is empty. 56 bool empty() { 57 if(q1.empty() && q2.empty()){ 58 return true; 59 } 60 return false; 61 } 62 };