LC-232 Implement Queue using Stacks

Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.

public class MyQueue {
    Stack stack1;
    Stack stack2;
    /** Initialize your data structure here. */
    public MyQueue() {
        stack1 = new Stack();
        stack2 = new Stack();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        stack2.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(stack1.isEmpty() == true) {
            stack2ToStack1();
        }
        if (stack1.isEmpty() != true) {
            return stack1.pop();
        } else {
            return -1;
        }
    }
    
    /** Get the front element. */
    public int peek() {
        if(stack1.isEmpty() == true) {
            stack2ToStack1();
        }
        if (stack1.isEmpty() != true) {
            return stack1.peek();
        } else {
            return -1;
        }
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        if(stack1.isEmpty() == true) {
            stack2ToStack1();
        }
        
        return stack1.isEmpty();
    }
    
    private void stack2ToStack1() {
        while (!stack2.empty()) {
            stack1.push(stack2.pop());
        }
    }
}

你可能感兴趣的:(LC-232 Implement Queue using Stacks)