Java Solution beats 100%


  • -1

    The idea is very simple, I consider FILO and LIFO are the same idea of stack, and because a stack is FILO and a queue is FIFO, then we can treat one of the stacks as FILO and one of them as LIFO and connect them together to form a FIFO queue.

    class MyQueue {
        
    	private Stack<Integer> in = new Stack<>();
    	private Stack<Integer> out = new Stack<>();
    
    	// Push element x to the back of queue.
    	public void push(int x) {
    		in.push(x);
    	}
    
    	// Removes the element from in front of queue.
    	public void pop() {
    		if (!out.isEmpty()) {
    			out.pop();
    		} else {
    			while (!in.isEmpty())
    				out.push(in.pop());
    			out.pop();
    		}
    	}
    
    	// Get the front element.
    	public int peek() {
    		if (!out.isEmpty())
    			return out.peek();
    		while (!in.isEmpty())
    			out.push(in.pop());
    		return out.peek();
    	}
    
    	// Return whether the queue is empty.
    	public boolean empty() {
    		return out.empty() && in.empty();
    	}
    }
    

Log in to reply
 

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