繁体   English   中英

在Java中遍历循环链表

[英]Traverse circular linked list in java

为节目()方法,我应该遍历每个节点在循环链表,起始于第一 ,以及打印用StdOut.println()的每个

我能够遍历并打印出循环链接列表中的每个节点,而无需重复。 我只是觉得有一种更好的方法可以编写此代码,但是我不知道如何在while循环中包含第一个Node。 如果我摆脱了while循环上方的那一行,那么最后一个节点不会被打印出来。 将其放在while循环之上。 有没有一种方法可以编写它并包含最后一个Node,而无需在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为空(也就是主节点为null)的情况下发生NullPointerException。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM