Last active
August 29, 2015 14:03
-
-
Save chrislukkk/6a9f88001b172ba629ed to your computer and use it in GitHub Desktop.
CareerCup_3.5 - Queue implemented by two stacks
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
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