LeetCode 232. Implement Queue using Stacks
原题链接在这里:https://leetcode.com/problems/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.
- 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).
题解:
用Stack implement queue时,可以采用两个stack, add时就是一直像stk1中压栈.
When poll or peek, if stk2 is empty, pop all the nums in stk1 and add them to stk2 one by one.
Now the top of stk2 is the expected result.
Time Complexity: push, O(1). pop, O(n), n is current number of integers in stack. peek O(n). empty O(1).
Space: O(n), 两个stack.
AC Java:
1 class MyQueue { 2 Stack<Integer> stk1; 3 Stack<Integer> stk2; 4 5 /** Initialize your data structure here. */ 6 public MyQueue() { 7 stk1 = new Stack<>(); 8 stk2 = new Stack<>(); 9 } 10 11 /** Push element x to the back of queue. */ 12 public void push(int x) { 13 stk1.push(x); 14 } 15 16 /** Removes the element from in front of queue and returns that element. */ 17 public int pop() { 18 if(stk2.isEmpty()){ 19 while(!stk1.isEmpty()){ 20 stk2.push(stk1.pop()); 21 } 22 } 23 24 return stk2.pop(); 25 } 26 27 /** Get the front element. */ 28 public int peek() { 29 if(stk2.isEmpty()){ 30 while(!stk1.isEmpty()){ 31 stk2.push(stk1.pop()); 32 } 33 } 34 35 return stk2.peek(); 36 } 37 38 /** Returns whether the queue is empty. */ 39 public boolean empty() { 40 return stk1.isEmpty() && stk2.isEmpty(); 41 } 42 } 43 44 /** 45 * Your MyQueue object will be instantiated and called as such: 46 * MyQueue obj = new MyQueue(); 47 * obj.push(x); 48 * int param_2 = obj.pop(); 49 * int param_3 = obj.peek(); 50 * boolean param_4 = obj.empty(); 51 */
AC C++:
1 class MyQueue { 2 public: 3 stack<int> stk1, stk2; 4 MyQueue() { 5 } 6 7 void push(int x) { 8 stk1.push(x); 9 } 10 11 int pop() { 12 if(stk2.empty()){ 13 while(!stk1.empty()){ 14 stk2.push(stk1.top()); 15 stk1.pop(); 16 } 17 } 18 19 int res = stk2.top(); 20 stk2.pop(); 21 return res; 22 } 23 24 int peek() { 25 if(stk2.empty()){ 26 while(!stk1.empty()){ 27 stk2.push(stk1.top()); 28 stk1.pop(); 29 } 30 } 31 32 return stk2.top(); 33 } 34 35 bool empty() { 36 return stk1.empty() && stk2.empty(); 37 } 38 }; 39 40 /** 41 * Your MyQueue object will be instantiated and called as such: 42 * MyQueue* obj = new MyQueue(); 43 * obj->push(x); 44 * int param_2 = obj->pop(); 45 * int param_3 = obj->peek(); 46 * bool param_4 = obj->empty(); 47 */