ImplementQueueUsingStacksOPT [source code]


public class ImplementQueueUsingStacksOPT {
static
/******************************************************************************/
public class MyQueue {
    private Stack<Integer> s1 = new Stack<>();
    private Stack<Integer> s2 = new Stack<>();
    private int front = 0;

    /** Initialize your data structure here. */
    public MyQueue() {
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        if (s1.empty()) front = x;
        s1.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if (s2.isEmpty()) {
            while (!s1.isEmpty()) s2.push(s1.pop());
        }
        return s2.pop();
    }

    /** Get the front element. */
    public int peek() {
        if (!s2.isEmpty()) return s2.peek();
        return front;
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return s1.isEmpty() && s2.isEmpty();
    }
}
/******************************************************************************/

    public static void main(String[] args) {
        ImplementQueueUsingStacksOPT.MyQueue tester = new ImplementQueueUsingStacksOPT.MyQueue();
        tester.push(1);
        tester.push(2);
        tester.push(3);
        System.out.println("peeking: " + tester.peek());
        for (int i = 0; i < 3; i++) System.out.println("popped: " + tester.pop());
        System.out.println(tester.empty());
    }
}

这个是 editorial 里面用两个 Stack 的最优解, 我这里修改了一下他当时代码里一些写的错误;
理论分析的速度是最强的, 但是实际上跑了一下速度并不如我自己的代码, 可能是因为 OJ 的 case 多数是 push 数量远高于 pop 的 case;

尽管如此, 这个 solution 的思想还是非常值得学习的;


Problem Description

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, 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).
Difficulty:Easy
Category:Algorithms
Acceptance:36.40%
Contributor: LeetCode
Companies
microsoft bloomberg
Related Topics
stack design
Similar Questions
Implement Stack using Queues

/**

  • Your MyQueue object will be instantiated and called as such:
  • MyQueue obj = new MyQueue();
  • obj.push(x);
  • int param_2 = obj.pop();
  • int param_3 = obj.peek();
  • boolean param_4 = obj.empty();
    */

results matching ""

    No results matching ""