Java Concise O(N) solution


  • 0
    W
    class MyStack {
        private Queue<Integer> queue1=new LinkedList<Integer>();
        private Queue<Integer> queue2=new LinkedList<Integer>();
        // Push element x onto stack.
        public void push(int x) {
            Queue<Integer> queueEmpty=queue1.isEmpty()?queue1:queue2;
            Queue<Integer> queueUse=queue1.isEmpty()?queue2:queue1;
            queueEmpty.add(x);
            while(!queueUse.isEmpty())
                queueEmpty.add(queueUse.poll());
        }
    
        // Removes the element on top of the stack.
        public void pop() {
            Queue<Integer> queueUse=queue1.isEmpty()?queue2:queue1;
            queueUse.poll();
        }
    
        // Get the top element.
        public int top() {
             Queue<Integer> queueUse=queue1.isEmpty()?queue2:queue1;
             return queueUse.peek();
        }
    
        // Return whether the stack is empty.
        public boolean empty() {
            return queue1.isEmpty() && queue2.isEmpty();
        }
    }

Log in to reply
 

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