Advertisement
tanglinghui

ctciCh3Q5

Jun 8th, 2012
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.73 KB | None | 0 0
  1. import java.util.Stack;
  2.  
  3. public class MyQueue {
  4.     private Stack<Integer> oldStack;
  5.     private Stack<Integer> newStack;
  6.    
  7.     public MyQueue(){
  8.         oldStack = new Stack<Integer>();
  9.         newStack = new Stack<Integer>();
  10.     }
  11.    
  12.     public void enqueue(int data){
  13.         newStack.push(data);
  14.     }
  15.    
  16.     public Integer dequeue(){
  17.         /*shift element from newStack to oldStack, while reverse the element order*/
  18.         shift(newStack, oldStack);
  19.         return oldStack.pop();
  20.     }
  21.    
  22.     public int size(){
  23.         return oldStack.size()+newStack.size();
  24.     }
  25.    
  26.     private void shift(Stack<Integer> src, Stack<Integer> dest){
  27.         /*only when oldStack is empty do we have to do the shift*/
  28.         if(dest.isEmpty()){
  29.             while(!src.isEmpty()){
  30.                 dest.push(src.pop());
  31.             }
  32.         }
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement