原题链接在这里: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).
题解:
与Implement Stack using Queues相对应.
用Stack implement queue时,可以采用两个stack, add时就是一直像stk1中压栈。
poll()时把stk1的所有元素逐个压入另一个stack stk2中,现在stk2最上面的元素就是最先来的的, pop()之后再把剩下的压回到stk1中。
peek()与poll()类似,但这次不用pop(), 只需peek()出一个值返回。
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 public class MyQueue { 2 Stack<Integer> stk1; 3 Stack<Integer> stk2; 4 5 /** Initialize your data structure here. */ 6 public MyQueue() { 7 stk1 = new Stack<Integer>(); 8 stk2 = new Stack<Integer>(); 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 while(!stk1.isEmpty()){ 19 stk2.push(stk1.pop()); 20 } 21 int res = 0; 22 if(!stk2.isEmpty()){ 23 res = stk2.pop(); 24 } 25 while(!stk2.isEmpty()){ 26 stk1.push(stk2.pop()); 27 } 28 return res; 29 } 30 31 /** Get the front element. */ 32 public int peek() { 33 while(!stk1.isEmpty()){ 34 stk2.push(stk1.pop()); 35 } 36 int res = 0; 37 if(!stk2.isEmpty()){ 38 res = stk2.peek(); 39 } 40 while(!stk2.isEmpty()){ 41 stk1.push(stk2.pop()); 42 } 43 return res; 44 } 45 46 /** Returns whether the queue is empty. */ 47 public boolean empty() { 48 return stk1.isEmpty(); 49 } 50 } 51 52 /** 53 * Your MyQueue object will be instantiated and called as such: 54 * MyQueue obj = new MyQueue(); 55 * obj.push(x); 56 * int param_2 = obj.pop(); 57 * int param_3 = obj.peek(); 58 * boolean param_4 = obj.empty(); 59 */