Created
July 3, 2014 06:44
-
-
Save JoyceeLee/4cd3b04782250d47aa69 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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