My java solution using two queues


  • 0
    D
    class MyStack {
        Queue<Integer> q1 = new LinkedList<Integer>();
        Queue<Integer> q2 = new LinkedList<Integer>();
        
        // Push element x onto stack.
        public void push(int x) {
            if(!q2.isEmpty()) {
                q2.offer(x);
                return;
            }
            q1.offer(x);
        }
    
        // Removes the element on top of the stack.
        public void pop() {
            if(!q1.isEmpty()) {
                while(q1.size()>1){
                    q2.offer(q1.poll());
                }
                q1.poll();
            } else {
                while(q2.size()>1){
                    q1.offer(q2.poll());
                }
                q2.poll();
            }
            
        }
    
        // Get the top element.
        public int top() {
            if(!q1.isEmpty()) {
                while(q1.size()>1){
                    q2.offer(q1.poll());
                }
                int top = q1.poll();
                q2.offer(top);
                return top;
            } else {
                while(q2.size()>1){
                    q1.offer(q2.poll());
                }
                int top = q2.poll();
                q1.offer(top);
                return top;
            }
        }
    
        // Return whether the stack is empty.
        public boolean empty() {
            return q1.isEmpty()&&q2.isEmpty();
        }
    }

Log in to reply
 

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