Queue via Stacks

作者 QIFAN 日期 2016-10-03
Queue via Stacks

Implement a MyQueue class which implements a queue using two stacks.

思路

两个stack相互调换。

解题

public class MyQueue<T> {
Stack<T> stackNewest, stackOldest;
public MyQueue() {
stackNewest new Stack<T>();
stackOldest = new Stack<T>();
}
public int size() {
return stackNewest.size() + stackOldest.size();
}
public void add(T value) {
stackNewest.push(value);
}
private void shiftStacks() {
if (stackOldest.isEmpty()) {
while (!stackNewest.isEmpty()) {
stackOldest.push(stackNewest.pop());
}
}
}
public T peek() {
shiftStacks(); // Ensure stackOldest has the current elements
return stackOldest.peek(); // retrieve the oldest item.
}
public T remove() {
shiftStacks(); // Ensure stackOldest has the current elements
return;
}
}