使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
解:
用数组或java的Stack类都可以,拿两个栈,一个push另一个pop,只要是判断好出栈的逻辑(当pop栈中没有元素时需要从push栈中拿出所有数据到pop栈,再进行下步操作):
class MyQueue {
Stack<Integer> pushStack;
Stack<Integer> popStack;
/**
* Initialize your data structure here.
*/
public MyQueue() {
pushStack = new Stack<>();
popStack = new Stack<>();
}
/**
* Push element x to the back of queue.
*/
public void push(int x) {
pushStack.push(x);
}
/**
* Removes the element from in front of queue and returns that element.
*/
public int pop() {
if (popStack.isEmpty()) {
while (!pushStack.isEmpty()) {
popStack.push(pushStack.pop());
}
}
return popStack.pop();
}
/**
* Get the front element.
*/
public int peek() {
if (popStack.isEmpty()) {
while (!pushStack.isEmpty()) {
popStack.push(pushStack.pop());
}
}
return popStack.peek();
}
/**
* Returns whether the queue is empty.
*/
public boolean empty() {
return pushStack.isEmpty() && popStack.isEmpty();
}
}