Created
July 5, 2014 17:16
-
-
Save bitcpf/36f4295d5b02d9b14d75 to your computer and use it in GitHub Desktop.
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 cc150_3_5; | |
import java.util.Stack; | |
public class StackQueue<T> { | |
private Stack<T> origin; | |
private Stack<T> reverse; | |
public StackQueue(){ | |
origin = new Stack<>(); | |
reverse = new Stack<>() ; | |
} | |
public void Insert(T item) { | |
origin.push(item); | |
} | |
public int size() { | |
return origin.size()+reverse.size(); | |
} | |
public T Deque() { | |
if (reverse.isEmpty()) { | |
while (!origin.isEmpty()) { | |
reverse.push(origin.pop()); | |
} | |
} | |
if (reverse.isEmpty()) | |
return null; | |
return reverse.pop(); | |
} | |
public boolean isEmpty() { | |
return origin.isEmpty() && reverse.isEmpty(); | |
} | |
public static void main(String[] args) { | |
StackQueue<Integer> queue = new StackQueue<>(); | |
for (int i = 1; i <= 10; i++) | |
queue.Insert(i); | |
for (int i = 1; i <= 5; i++) | |
System.out.println("Dequeue: " + queue.Deque()); | |
for (int i = 11; i <= 15; i++) | |
queue.Insert(i); | |
while (!queue.isEmpty()) | |
System.out.println("Dequeue: " + queue.Deque()); | |
//test dequeue empty stack | |
System.out.println("Dequeue: " + queue.Deque()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment