My Java Solution using 2 queues


  • 0
    Q

    I'm only using 3 queue operations: empty, poll, and offer.

    class MyStack {
        Queue<Integer> queue = new ArrayDeque<Integer>();
        Queue<Integer> backup = new ArrayDeque<Integer>();
        
        public void push(int x) {
        	queue.offer(x);
        }
    
        // Removes the element on top of the stack.
        public void pop() {
        	while (!queue.isEmpty()){
        		int n = queue.poll();
        		if (!queue.isEmpty()){
        			backup.offer(n);
        		}	
        	}
        	Queue<Integer> temp = queue;
        	queue = backup;
        	backup = temp;
        }
    
        // Get the top element.
        public int top() {
        	int n = 0;
        	while (!queue.isEmpty()){
        		n = queue.poll();
        		backup.offer(n);
        	}
        	Queue<Integer> temp = queue;
        	queue = backup;
        	backup = temp;
        	
        	return n;
        }
    
        // Return whether the stack is empty.
        public boolean empty() {
        	return queue.isEmpty();
        }
    }

Log in to reply
 

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