Java easy understanding solution using ArrayList


  • 0
    Y

    class MyStack {
    // Push element x onto stack.
    List<Integer> queue = new ArrayList<Integer>();

    public void push(int x) {
        queue.add(x);
    }
    
    // Removes the element on top of the stack.
    public void pop() {
        List<Integer> temp = new ArrayList<Integer>();
        while(queue.size() > 1) temp.add(queue.remove(0));
        while(temp.size() > 0) queue.add(temp.remove(0));
        queue.remove(0);
    }
    
    // Get the top element.
    public int top() {
        List<Integer> temp = new ArrayList<Integer>();
        while(queue.size() > 1) temp.add(queue.remove(0));
        int result = queue.remove(0);
        temp.add(result);
        while(temp.size() > 0) queue.add(temp.remove(0));
        return result;
    }
    
    // Return whether the stack is empty.
    public boolean empty() {
        return queue.isEmpty();
    }
    

    }


Log in to reply
 

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