题目要求
- 要求使用两个栈来实现一个队列的功能
- 实现addLast功能
- 实现pollFirst功能
- 实现peekFirst功能
- 实现isEmpty功能
代码实现
class MyQueue<T> {
private Stack<T> stack1;
private Stack<T> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void addLast(T val) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
stack2.push(val);
}
public T pollFirst() {
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
return stack1.pop();
}
public T peekFirst() {
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
return stack1.peek();
}
public boolean isEmpty() {
return stack1.isEmpty() && stack2.isEmpty();
}
}
测试代码
public static void main(String[] args) {
MyQueue<String> myQueue = new MyQueue<>();
myQueue.addLast("wenpan");
myQueue.addLast("hello");
myQueue.addLast("world");
myQueue.addLast("1");
myQueue.addLast("2");
myQueue.addLast("3");
for (int i = 0; i < 5; i++) {
String str = myQueue.pollFirst();
System.out.println(str);
}
myQueue.addLast("4");
myQueue.addLast("5");
while (!myQueue.isEmpty()) {
String str = myQueue.pollFirst();
System.out.println(str);
}
}
输出
wenpan
hello
world
1
2
3
4
5