Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Last active August 29, 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 chrislukkk/6a9f88001b172ba629ed to your computer and use it in GitHub Desktop.
Save chrislukkk/6a9f88001b172ba629ed to your computer and use it in GitHub Desktop.
CareerCup_3.5 - Queue implemented by two stacks
package Chapter3;
public class StackQueue<T> {
private Stack<T> fir;
private Stack<T> sec;
public StackQueue() {
fir = new Stack<>();
sec = new Stack<>();
}
public void enqueue(T value) {
fir.push(value);
}
public T dequeue() {
if (sec.isEmpty()) {
while (!fir.isEmpty()) {
sec.push(fir.pop());
}
}
if (sec.isEmpty())
return null;
return sec.pop();
}
public boolean isEmpty() {
return fir.isEmpty() && sec.isEmpty();
}
public static void main(String[] args) {
StackQueue<Integer> queue = new StackQueue<>();
for (int i = 1; i <= 10; i++)
queue.enqueue(i);
for (int i = 1; i <= 5; i++)
System.out.println("Dequeue: " + queue.dequeue());
for (int i = 11; i <= 15; i++)
queue.enqueue(i);
while (!queue.isEmpty())
System.out.println("Dequeue: " + queue.dequeue());
//test dequeue empty stack
System.out.println("Dequeue: " + queue.dequeue());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment