Java Solutions by using one queue and two queues


  • 0
    D
    Using two queues:
    class MyStack {
        Queue<Integer> q1 = new LinkedList<>();
        Queue<Integer> q2 = new LinkedList<>();
        public void push(int x) {
            q1.offer(x);
        }
        public void pop() {
            while(q1.size() != 1) {
                q2.offer(q1.poll());
            }
            q1.poll();
            while(!q2.isEmpty()) {
                q1.offer(q2.poll());
            }
        }
        public int top() {
            while(q1.size() != 1) {
                q2.offer(q1.poll());
            }
            int temp =  q1.peek();
            q2.offer(q1.poll());
            while(!q2.isEmpty()) {
                q1.offer(q2.poll());
            }
            return temp;
        }
        public boolean empty() {
            return q1.isEmpty();
        }
    }
    
    
    Using just one queue:
    class MyStack {
        Queue<Integer> q = new LinkedList<>();
        // Push element x onto stack.
        public void push(int x) {
            q.offer(x);
        }
    
        // Removes the element on top of the stack.
        public void pop() {
            int size = q.size();
            for (int i = 1; i < size; i++) {
                q.offer(q.poll());
            }
            q.poll();
        }
    
        // Get the top element.
        public int top() {
            int size = q.size();
            for (int i = 1; i < size; i++) {
                q.offer(q.poll());
            }
            int value = q.peek();
            q.offer(q.poll());
            return value;
        }
    
        // Return whether the stack is empty.
        public boolean empty() {
            return q.isEmpty();
        }
    }

Log in to reply
 

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