Java: Implement a queue by using two stacks. The queue should provide size(), isEmpty(), offer(), poll() and peek() operations. When the queue is empty, poll() and peek() should return null.

Assumptions:

The elements in the queue are all Integers.

size() should return the number of elements buffered in the queue.

isEmpty() should return true if there is no element buffered in the queue, false otherwise.

Approach: One Stack as push in another one as poll out. Notice: when out is empty, we need push all elements inside in stack to out stack.

public class Solution{
    private Deque<Integer> in;
    private Deque<Integer> out;
    private int size;

    public Solution() {
        in = new LinkedList<>();
        out = new LinkedList<>();
    }

    public int poll() {
        if (out.isEmpty()) {
            while (!in.isEmpty()) {
                out.offerFirst(in.pollFirst());
            }
        }
        return out.isEmpty() ? null : out.pollFirst();
    }

    public void offer(Integer element) {
        in.offerFirst(element);
    }

    public int peek() {
        if (out.isEmpty()) {
            while(!in.isEmpty()) {
                out.offerFirst(in.pollFirst());
            }
        }
        return out.isEmpty() ? null : out.peekFirst();
    }

    public int size() {
        return out.size() + in.size();
    }

    public boolean isEmpty() {
        return out.size() + in.size() == 0;
    }
}

results matching ""

    No results matching ""