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;
}
You can use a do-while loop to get rid of the line just before the while loop:
There's not much else you can do to improve the method.