Skip to content

Instantly share code, notes, and snippets.

@bitcpf
Created July 5, 2014 17:16
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 bitcpf/36f4295d5b02d9b14d75 to your computer and use it in GitHub Desktop.
Save bitcpf/36f4295d5b02d9b14d75 to your computer and use it in GitHub Desktop.
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