循環鏈表對於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