-
-
Save JamesJi9277/425d9a0b8ae477ab5aaa to your computer and use it in GitHub Desktop.
3.5.java
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
//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