One stack solution, using system stack, just provide a new idea


  • 4
    S
    class MyQueue {
        Stack<Integer> stack;
        boolean flag;
        int peekVal;
        
        public MyQueue() {
            stack = new Stack<Integer>();
            flag = false;
            peekVal = 0;
        }
        
        // Push element x to the back of queue.
        public void push(int x) {
            stack.push(x);
        }
        
        // Removes the element from in front of queue.
        public void pop() {
            if (!stack.isEmpty()) {
                int val = stack.pop();
                pop();
                if (flag == true) {
                    flag = false;
                } else {
                    stack.push(val);
                }
            } else {
                flag = true;
            }
        }
    
        // Get the front element.
        public int peek() {
            if (!stack.isEmpty()) {
                int val = stack.pop();
                peek();
                if (flag == true) {
                    flag = false;
                    peekVal = val;
                }
                stack.push(val);
            } else {
                flag = true;
            }
            return peekVal;
        }
    
        // Return whether the queue is empty.
        public boolean empty() {
            return stack.isEmpty();
        }
    }

Log in to reply
 

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