Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Last active August 29, 2015 14:03
Show Gist options
  • Save jingz8804/fa72f22071e2a45b30aa to your computer and use it in GitHub Desktop.
Save jingz8804/fa72f22071e2a45b30aa to your computer and use it in GitHub Desktop.
#ctci
import java.util.Stack;
public class MyQueue<E>{
private Stack<E> s1;
private Stack<E> s2;
private int N = 0;
public MyQueue(){
s1 = new Stack<E>();
s2 = new Stack<E>();
}
public void enqueue(E val){
s1.push(val);
N++;
}
public E dequeue() throws Exception{
if(N == 0) throw new Exception("The queue is already empty!");
if(s2.size() == 0) moveFromS1toS2();
N--;
return s2.pop();
}
public int size(){
return N;
}
private void moveFromS1toS2(){
while(s1.size() > 0){
E tmp = s1.pop();
s2.push(tmp);
}
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
MyQueue<Integer> queue = new MyQueue<Integer>();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment