maaartinus
maaartinus

Reputation: 46422

Using a stack as a Queue in Java

I need to process a tree in different orders, let's say BFS and DFS. Both is easy by using a queue or a stack, however, I'm missing a proper interface in Java allowing to do something like

QueueOrStack<N> pending = ...
while (!pending.isEmpty()) {
    N node = pending.poll(); // <----- this is the problem
    pending.addAll(node.children());
    process(node);
}

There's no real problem, I can encapsulate an ArrayList into something implementing Queue1, however I'd bet I'm overlooking something in the Java Collection Framework. Or is it really missing?

__

1 or use a newest-first comparator with a PriorityQueue, which is probably a dumb idea

Upvotes: 2

Views: 191

Answers (1)

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45576

There is such a structure.

It is called ArrayDeque -> http://docs.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html

Upvotes: 5

Related Questions