Skip to content

Instantly share code, notes, and snippets.

@JoyceeLee
Created July 3, 2014 06:44
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 JoyceeLee/4cd3b04782250d47aa69 to your computer and use it in GitHub Desktop.
Save JoyceeLee/4cd3b04782250d47aa69 to your computer and use it in GitHub Desktop.
/*3.5 Implement a MyQueue class which implements a queue using two stacks.*/
public class MyQueue<T> {
Stack<T> stackNewest, stackOldest;
public MyQueue() {
stackNewest = new Stack<T>();
stackOldest = new Stack<T>();
}
public int size() {
return stackNewest.size()+stackOldest.size();
}
public void add(T value) {
stackNewest.push(value);
}
private void shiftStacks() {
if(stackOldest.isEmpty()) {
while(!stackNewest.isEmpty()) {
stackOldest.push(stackNewest.pop());
}
}
}
public T peek() {
shiftStack();
return stackOldest.peek();
}
public T remove() {
shiftStacks();
return stackOldest.pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment