[LeetCode]Implement Queue using Stacks
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).
使用 两个栈可以实现队列。
注意,栈是先入后出,队列是先入先出。
1 class Queue { 2 public: 3 stack<int> s1,s2; 4 // Push element x to the back of queue. 5 void push(int x) { 6 s1.push(x); 7 } 8 9 // Removes the element from in front of queue. 10 void pop(void) { 11 if(!s2.empty()) 12 { 13 s2.pop(); 14 } 15 else 16 { 17 while(!s1.empty()) 18 { 19 int temp = s1.top(); 20 s1.pop(); 21 s2.push(temp); 22 } 23 if(!s2.empty()) 24 { 25 s2.pop(); 26 } 27 } 28 } 29 30 // Get the front element. 31 int peek(void) { 32 if(!s2.empty()) 33 { 34 return s2.top(); 35 } 36 else 37 { 38 while(!s1.empty()) 39 { 40 int temp = s1.top(); 41 s1.pop(); 42 s2.push(temp); 43 } 44 if(!s2.empty()) 45 { 46 return s2.top(); 47 } 48 } 49 } 50 51 // Return whether the queue is empty. 52 bool empty(void) { 53 if(s1.empty() && s2.empty()) return true; 54 else return false; 55 } 56 };