Skip to content

Instantly share code, notes, and snippets.

@anandankm
Created November 27, 2012 06:18
Show Gist options
  • Save anandankm/4152688 to your computer and use it in GitHub Desktop.
Save anandankm/4152688 to your computer and use it in GitHub Desktop.
A Queue using a stack. This uses an additional stack from the stack memory through recursion.
import java.util.Stack;
public class QueueFromStack<E> {
Stack<E> stack = new Stack<E>();
public void push(E element) {
if (this.stack.empty()) {
this.stack.push(element);
} else {
E e = this.stack.pop();
this.push(element);
this.stack.push(e);
}
}
public E pop() {
if (!this.stack.empty()) {
return this.stack.pop();
} else {
return null;
}
}
public static void main(String[] args) {
QueueFromStack<String> queue = new QueueFromStack<String>();
queue.push("A");
queue.push("B");
queue.push("C");
queue.push("D");
queue.push("E");
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment