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.
Notes:
  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is 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  */

类似Implement Stack using Queues. 

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825030.html