Traverse circular linked list in java

2.7k views Asked by At

For the show() method, I'm supposed to traverse each Node in the circular linked list, starting at first, and printing each Point using StdOut.println().

I am able to traverse and print out each Node in the circular linked list without repeating. I just feel like there's a better way to write this, but I can't figure out how to include the first Node in the while loop. If I get rid of the line above the while loop, then the last node doesn't get printed out. Putting it above the while loop does. Is there a way to write it and have the last Node included without writing the line above the while loop?

public class Tour {
// Nested class Node to contain a Point and a reference
// to the next Node in the tour
private class Node {
    Point p;
    Node next;
}

private Node first;
//private Node last;
private int size;
private double distance;

// Create an empty Tour
// Constructor that creates an empty tour
public Tour()
{
    first = null;
    //last = null;
    size = 0;
    distance = 0.0;
}

// Create a 4 point tour a->b->c->d->a
// Constructor that creates a 4 point tour and is
// intended to assist with debugging
public Tour(Point a, Point b, Point c, Point d)
{   
    Node one = new Node();
    Node two = new Node();
    Node three = new Node();
    Node four = new Node();

    one.p = a;
    two.p = b;
    three.p = c;
    four.p = d;

    one.next = two;
    two.next = three;
    three.next = four;
    four.next = one;

    first = one;
    //last = four;
}

// Print the tour to standard output
// Print constituent points to standard output
public void show()
{
    Node tmp = first;

    if (tmp == null)
    {
        StdOut.println("");
        return;
    }

    StdOut.println(tmp.p.toString());
    while (tmp.next != first)
    {
        tmp = tmp.next;
        StdOut.println(tmp.p.toString());
    }
    return;
}
2

There are 2 answers

1
fabian On BEST ANSWER

You can use a do-while loop to get rid of the line just before the while loop:

Node tmp = first;

if (tmp == null)
{
    StdOut.println("");
    return;
}

do
{
    StdOut.println(tmp.p.toString());
    tmp = tmp.next;
} while (tmp != first);

There's not much else you can do to improve the method.

0
him On

change it to a do-while loop. you'll just have to include an if test inside to prevent a NullPointerException for the case where the CLL is empty (aka the primary node is null).