[leetcode] 232. 用栈实现队列

LeetCode.232 用栈实现队列

public class MyQueue {

	Stack<Integer> push;
	Stack<Integer> pop;

	/**
	 * Initialize your data structure here.
	 */
	public MyQueue() {
		push = new Stack<Integer>();
		pop = new Stack<Integer>();
	}

	/**
	 * Push element x to the back of queue.
	 */
	public void push(int x) {
		push.push(x);
	}

	/**
	 * Removes the element from in front of queue and returns that element.
	 */
	public int pop() {
		if (pop.isEmpty()) {
			while (!push.isEmpty()) {
				pop.push(push.pop());
			}
		}

		return pop.pop();
	}

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

		return pop.peek();
	}

	/**
	 * Returns whether the queue is empty.
	 */
	public boolean empty() {
		return pop.isEmpty() && push.isEmpty();
	}
}
posted @ 2019-01-18 00:17  ACBingo  阅读(...)  评论(...编辑  收藏