LeetCode Implement Stack using Queues

原题链接在这里:https://leetcode.com/problems/implement-stack-using-queues/

题目:

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Notes:

    • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
    • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
    • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

题解:

Implement Queue using Stacks相对应。

用一个queue来实现stack. push时从queue尾add进去, 然后rotate了que.size()-1次.

pop()时从queue首 poll 出一个. top()是 peek() 一下.

Time Complexity: push, O(n). pop, O(1). peek, O(1). empty, O(1).

Space: O(n), queue size.

AC java:

 1 public class MyStack {
 2     
 3     Queue<Integer> que;
 4     /** Initialize your data structure here. */
 5     public MyStack() {
 6         que = new LinkedList<Integer>();
 7     }
 8     
 9     /** Push element x onto stack. */
10     public void push(int x) {
11         que.offer(x);
12         for(int i = 0; i<que.size()-1; i++){
13             que.offer(que.poll());
14         }
15     }
16     
17     /** Removes the element on top of the stack and returns that element. */
18     public int pop() {
19         return que.poll();
20     }
21     
22     /** Get the top element. */
23     public int top() {
24         return que.peek();
25     }
26     
27     /** Returns whether the stack is empty. */
28     public boolean empty() {
29         return que.isEmpty();
30     }
31 }
32 
33 /**
34  * Your MyStack object will be instantiated and called as such:
35  * MyStack obj = new MyStack();
36  * obj.push(x);
37  * int param_2 = obj.pop();
38  * int param_3 = obj.top();
39  * boolean param_4 = obj.empty();
40  */
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825031.html