4. Stack and Queue

Queue

Deque<Integer> queue = new LinkedList<>();

  • add

  • poll

  • peek

Stack

Deque<Integer> queue = new LinkedList<>();

  • push

  • pop

  • peek

Implement stack by queue

1. Two Queue, Push O(1), Pop O(n)

class MyStack {
    private Deque<Integer> q1; 
    private Deque<Integer> q2;
    private int top;

    public MyStack() {
        q1 = new LinkedList<>();
        q2 = new LinkedList<>();
    }

    public void push(int x) {
        q1.add(x);
        top = x;
    }

    public int pop() {
        while(q1.size() > 1){
            top = q1.poll();
            q2.add(top);
        }
        Deque<Integer> tmp = q1;
        q1 = q2;
        q2 = tmp;
        return q2.poll();
    }

    public int top() {
        return top;
    }

    public boolean empty() {
        return q1.isEmpty();
    }
}

2. Two Queue, Push O(n), Pop(1)

3. One Queue, Push O(n), Pop(1)

Implement Queue by stack

1. Two stacks, add O(n), poll O(1)

2. Two stacks, add average O(1), poll O(1)

Last updated

Was this helpful?