Java solution that only modify pop function


  • 0
    B
    class MyStack {
        // Push element x onto stack.
        private Queue<Integer> Q = null;
        int top;
        MyStack () {
            this.Q = new LinkedList<Integer>();
        }
    
        public void push(int x) {
            this.Q.add(x);
            this.top = x;
        }
    
        // Removes the element on top of the stack.
        public void pop() {
            Queue<Integer> NewQ = new LinkedList<Integer>();
            while (this.Q.size()>2) {
                NewQ.add(this.Q.poll());
            }
            if (!this.Q.isEmpty()) {
                this.top = this.Q.poll();
                if (!this.Q.isEmpty()) {
                    NewQ.add(this.top);
                }
            }
            this.Q = NewQ;
        }
    
        // Get the top element.
        public int top() {
            if (!this.Q.isEmpty()) {
                return this.top;
            } else {
                return 0;
            }
        }
    
        // Return whether the stack is empty.
        public boolean empty() {
            return (this.Q==null)? true:this.Q.isEmpty();
        }
    }

Log in to reply
 

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