遍历java中的循环链表

时间:2014-11-23 17:13:05

标签: java linked-list circular-list

对于show()方法,我应该遍历循环链表中的每个节点,从第一个开始,然后打印每个 Point < / strong>使用StdOut.println()。

我能够遍历并打印出圆形链表中的每个节点而不重复。我觉得有更好的方法来编写它,但我无法弄清楚如何在while循环中包含第一个Node。如果我摆脱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;
}

2 个答案:

答案 0 :(得分:1)

您可以使用do-while循环来摆脱while循环之前的行:

Node tmp = first;

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

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

你无法改进方法。

答案 1 :(得分:0)

将其更改为do-while循环。你只需要在里面包含一个if测试,以防止在CLL为空(也就是主节点为空)的情况下出现NullPointerException。