java 用兩個棧實現隊列

題目:

 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.
Notes:

    You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.

    You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

解法如下:

class MyQueue {

    // Push element x to the back of queue.
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    public void push(int x) {
        stack1.push(x);
    }

    // Removes the element from in front of queue.
    public void pop() {
        if(!stack2.isEmpty()) stack2.pop();
        else{
            while(!stack1.isEmpty()) stack2.push(stack1.pop());
            stack2.pop();
        }
    }

    // Get the front element.
    public int peek() {
        if(!stack2.isEmpty()) return stack2.peek();
        else{
            while(!stack1.isEmpty()) stack2.push(stack1.pop());
            return stack2.peek();
        }
    }

    // Return whether the queue is empty.
    public boolean empty() {
        return stack1.empty()&&stack2.empty();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章