OMeihls
OMeihls

Reputation: 47

How can I print all the elements in a Generic Linked List Queue?

This is the current method I'm working with. newt is the name of the Generic LinkedList Queue.

newt.peek() returns the data inside of the head of the queue.

I'm not sure how to go through each element in the queue (this is my first time working with a queue) and print the data in each one.

//Print all elements of the queue.
public void printProcessQueue() {
    boolean hasMore = true;
    while (hasMore) {
        if (newt.peek() != null) {
            System.out.println(newt.head);
            //Cannot figure out how to get the next in queue
        }
    }
}

Upvotes: 1

Views: 432

Answers (1)

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 28968

how to go through each element in the queue and print the data in each one

You can do it by removing the head of the queue in a loop until the queue is not empty:

public void printQueue() {
    while (!queue.isEmpty()) {              // basically you can use `queue.peek() != null`, but `isEmpty()` is more preferable because it's more expressive
        System.out.println(queue.remove()); // or queue.poll()
    }
}

If you're not OK with removing all the elements from the queue, then you can make use of the iterator. But note that iterator created over the elements of the queue will not necessarily guarantee to traverse them in any specific order. It will depend on the implementation: for instance, ArrayDeque and LinkedList give you such guarantee, but PriorityQueue doesn't.

public void printQueue() {
    Iterator<MyType> iterator = queue.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
}

Sidenote: when you need a Queue (or Deque) favor ArrayDeque over LinkedList as a more performant implementation.

Upvotes: 2

Related Questions