循环链表对于show()方法,我应该遍历每个节点在循环链表,起始于第一,并且印刷是使用StdOut.println每个点() 。遍历在Java
我能遍历并打印出循环链表中的每个节点而不重复。我只是觉得有更好的方法来写这个,但我不知道如何在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;
}
实际上,那应该是'while(tmp!= first)' – fishinear 2014-11-23 17:31:11
@fishinear:的确,thanx。 – fabian 2014-11-23 17:37:05
@fabian:那就做到了!谢谢! – 2014-11-23 18:49:53