Skip to content

Instantly share code, notes, and snippets.

@JamesJi9277
Created April 18, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesJi9277/425d9a0b8ae477ab5aaa to your computer and use it in GitHub Desktop.
Save JamesJi9277/425d9a0b8ae477ab5aaa to your computer and use it in GitHub Desktop.
3.5.java
//implement a MyQueue class which implements a queue using two stacks
public class MyQueue<T>{
Stack<T> stackNew, stackOld;
public MyQueue(){
stackNew = new Stack<T>();
stackOld = new Stack<T>();
}
public int size(){
return stackNew.size() + stackOld.size();
}
public void add(T value){
stackNew.push(value);
}
private void shiftStacks(){
if(stackOld.isEmpty())
{
while(!stackNew.isEmpty())
stackOld.push(stackNew.pop());
}
}
public T peek(){
shiftStacks();
return stackOld.peek();
}
public T remove(){
shiftStacks();
return stackOld.pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment