Created
November 27, 2012 06:18
-
-
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.
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
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