Java solution: Use only pure queue functions which without peek(), get(), isEmpty() pop(), pollFirst() functions


  • 0
    L

    Java solution: Use only pure queue functions which without peek(), get(), isEmpty() pop(), pollFirst() functions
    class MyStack {
    Queue<Integer> que = new LinkedList<>();
    int size;
    int last;
    /** Initialize your data structure here. */
    public MyStack() {
    size = 0;
    }

    /** Push element x onto stack. */
    public void push(int x) {
        que.add(x);
        last = x;
        ++ size;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        // if (size == 0){
        //     return null;
        // }
        for (int i = 0; i < size - 1; ++ i){
            last = que.poll();
            que.add(last);
        }
        -- size;
        return que.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return last;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        if (size == 0){
            return true;
        }
        return false;
    }
    

    }


Log in to reply
 

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