对于show()方法,我应该遍历循环链表中的每个节点,从一开始,并使用StdOut.println()打印每个点。
我能够遍历和打印出循环链表中的每个节点,而无需重复。我只是觉得有更好的方法来写这个,但我无法弄清楚如何在 while 循环中包含第一个节点。如果我去掉 while 循环上方的行,那么最后一个节点就不会被打印出来。把它放在 while 循环之上就可以了。有没有办法编写它并包含最后一个节点,而无需在 while 循环上方写入行?
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;
}
您可以使用 do-while 循环来摆脱 while 循环之前的行:
Node tmp = first;
if (tmp == null)
{
StdOut.println("");
return;
}
do
{
StdOut.println(tmp.p.toString());
tmp = tmp.next;
} while (tmp != first);
您可以做太多其他事情来改进该方法。
更改为do-while循环。 您只需要在内部包含一个 if 测试,以防止在 CLL 为空(即主节点为空)的情况下出现 NullPointerException。