Elegant Java Solution Beating 96%


  • 0
    A
    private Queue<Integer> Q1 = new LinkedList<>();
    private Queue<Integer> Q2 = new LinkedList<>();
    
    // Push element x onto stack.
    public void push(int x) {
        Q2.offer(x);
        
        while (!Q1.isEmpty()) {
            Q2.offer(Q1.poll());
        }
        Queue<Integer> temp = Q1;
        Q1 = Q2;
        Q2 = temp;
    }
    
    // Removes the element on top of the stack.
    public void pop() {
        if (!empty()) {
            Q1.poll();
        }
    }
    
    // Get the top element.
    public int top() {
        if (!empty()) {
            return Q1.peek();
        }
        return 0;
    }
    
    // Return whether the stack is empty.
    public boolean empty() {
        return Q1.isEmpty();
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.