程序员面试金典--题目解析-3.5 实现一个MyQueue类,使用两个栈实现一个队列

3.5 题目:

实现一个MyQueue类,使用两个栈实现一个队列


解法:

使用一个new栈push数据,一个old栈pop或peek数据

前提是保证把new栈pop出的所有数据,push进old栈,这样old栈的栈顶存放的就是最旧的数据。

另外,为了提高效率,等需要peek或remove时,检测old栈是否为空,old栈为空时,把所有new栈中的数据弹出存入old栈。


  1. package Queue;  
  2.   
  3. import java.util.Stack;  
  4.   
  5. public class MyQueue<T> {  
  6.     private Stack<T> stackNewest;  
  7.     private Stack<T> stackOldest;  
  8.       
  9.     public MyQueue() {  
  10.         this.stackNewest = new Stack<>();  
  11.         this.stackOldest = new Stack<>();  
  12.     }  
  13.       
  14.     public void add(T value){  
  15.         stackNewest.push(value);  
  16.     }  
  17.       
  18.     public T peek(){  
  19.         shiftStacks();  
  20.         return stackOldest.peek();  
  21.     }  
  22.       
  23.     public T remove(){  
  24.         shiftStacks();  
  25.         return stackOldest.pop();  
  26.     }  
  27.       
  28.     public int size(){  
  29.         return stackNewest.size() + stackOldest.size();  
  30.     }  
  31.       
  32.     private void shiftStacks() {  
  33.         if(stackOldest.isEmpty()){  
  34.             while(!stackNewest.isEmpty()){  
  35.                 stackOldest.push(stackNewest.pop());  
  36.             }  
  37.         }  
  38.     }  
  39. }  

测试用例:

  1. @Test  
  2.     public void test_3_5() {  
  3.         MyQueue<Integer> queue = new MyQueue<>();  
  4.         queue.add(1);  
  5.         queue.add(2);  
  6.         queue.add(3);  
  7.         System.out.println(queue.peek());  
  8.     }  


测试结果:

1

猜你喜欢

转载自blog.csdn.net/kingmore96/article/details/80102445