3.5 题目:
实现一个MyQueue类,使用两个栈实现一个队列
解法:
使用一个new栈push数据,一个old栈pop或peek数据
前提是保证把new栈pop出的所有数据,push进old栈,这样old栈的栈顶存放的就是最旧的数据。
另外,为了提高效率,等需要peek或remove时,检测old栈是否为空,old栈为空时,把所有new栈中的数据弹出存入old栈。
- package Queue;
- import java.util.Stack;
- public class MyQueue<T> {
- private Stack<T> stackNewest;
- private Stack<T> stackOldest;
- public MyQueue() {
- this.stackNewest = new Stack<>();
- this.stackOldest = new Stack<>();
- }
- public void add(T value){
- stackNewest.push(value);
- }
- public T peek(){
- shiftStacks();
- return stackOldest.peek();
- }
- public T remove(){
- shiftStacks();
- return stackOldest.pop();
- }
- public int size(){
- return stackNewest.size() + stackOldest.size();
- }
- private void shiftStacks() {
- if(stackOldest.isEmpty()){
- while(!stackNewest.isEmpty()){
- stackOldest.push(stackNewest.pop());
- }
- }
- }
- }
测试用例:
- @Test
- public void test_3_5() {
- MyQueue<Integer> queue = new MyQueue<>();
- queue.add(1);
- queue.add(2);
- queue.add(3);
- System.out.println(queue.peek());
- }
测试结果:
1