leetcode Implement Queue using Stacks
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
Notes:
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
不难,想明白就好,貌似之前看到过这样的题目;一个栈用来存放push的东西,每次需要pop或者peek的时候,再将该栈的所有数据移到另外一个栈里。
1 class Queue { 2 public: 3 stack<int> Squeue1; 4 stack<int> Squeue2; 5 // Push element x to the back of queue. 6 void push(int x) { 7 Squeue1.push(x); 8 } 9 10 // Removes the element from in front of queue. 11 void pop(void) { 12 13 int q; 14 if(Squeue2.empty()){ 15 while(!Squeue1.empty()){ 16 q=Squeue1.top(); 17 Squeue2.push(q); 18 Squeue1.pop(); 19 } 20 } 21 Squeue2.pop(); 22 } 23 24 25 26 // Get the front element. 27 int peek(void) { 28 int p,q; 29 if(Squeue2.empty()){ 30 while(!Squeue1.empty()){ 31 q=Squeue1.top(); 32 Squeue2.push(q); 33 Squeue1.pop(); 34 } 35 } 36 p=Squeue2.top(); 37 return p; 38 } 39 40 // Return whether the queue is empty. 41 bool empty(void) { 42 if(Squeue1.empty()&&Squeue2.empty()) return true; 43 else return false; 44 45 } 46 };