Java:链接列表节点在我的代码中不起作用

时间:2019-07-20 04:53:53

标签: java arrays linked-list nodes

因此,我非常了解链表,并且创建节点非常令人困惑。对于我的程序,我必须在主类中创建一个名为insertAfter(TrackerNode nodeLoc)的方法,该方法引用我为在节点中插入数据而创建的另一个类。首先,用户输入的是节点总数,然后是每个节点的数据(名称和年龄)。

1 个答案:

答案 0 :(得分:0)

所发布的代码存在一些问题,age字段(根据请求的输出)应为int,并且您需要记住声明age的顺序和name在您的构造函数中。也可以使用this()来缩短重复的构造函数。并且我宁愿使用toString()而不是自定义数据转储方法。喜欢,

public class TrackerNode {
    private int age;
    private String name;
    private TrackerNode nextNodeRef; // Reference to the next node

    public TrackerNode() {
        this("", 0);
    }

    public TrackerNode(String name, int age) {
        this(name, age, null);
    }

    public TrackerNode(String name, int age, TrackerNode nextLoc) {
        this.age = age;
        this.name = name;
        this.nextNodeRef = nextLoc;
    }

    public void insertAfter(TrackerNode nodeLoc) {
        TrackerNode tmpNext = this.nextNodeRef;
        this.nextNodeRef = nodeLoc;
        nodeLoc.nextNodeRef = tmpNext;
    }

    // Get location pointed by nextNodeRef
    public TrackerNode getNext() {
        return this.nextNodeRef;
    }

    @Override
    public String toString() {
        return String.format("%s, %d", this.name, this.age);
    }
}

然后,您的main循环实际上应该使用您阅读的i,并且在打印之前需要重置到头节点。像

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);

    // References for TrackerNode objects
    TrackerNode headNode = null, currNode = null, lastNode = null;

    // Scan the number of nodes
    int i = scnr.nextInt();

    // in data and insert into the linked list
    for (int k = 0; k < i; k++) {
        String name = scnr.next();
        int age = scnr.nextInt();
        scnr.nextLine();
        if (lastNode != null) {
            currNode = new TrackerNode(name, age);
            lastNode.insertAfter(currNode);
        } else {
            currNode = headNode = new TrackerNode(name, age);
        }
        lastNode = currNode;
    }

    // Print linked list
    currNode = headNode;
    while (currNode != null) {
        System.out.println(currNode);
        currNode = currNode.getNext();
    }
}

我用您提供的输入进行了测试(并且我收到的输出似乎符合发布的期望):

3
John
22
Silver
24
Smith
21
John, 22
Silver, 24
Smith, 21