【问题标题】:Java: Linked list node isn't working in my codeJava:链接列表节点在我的代码中不起作用
【发布时间】:2019-07-20 04:53:53
【问题描述】:

所以我非常擅长链表,创建节点非常混乱。对于我的程序,我必须在名为 insertAfter(TrackerNode nodeLoc) 的主类中创建一个方法,该方法引用我为在节点中插入数据而创建的另一个类。用户输入最初是节点总数,然后是每个节点的数据(姓名和年龄)。

【问题讨论】:

    标签: java arrays linked-list nodes


    【解决方案1】:

    您发布的代码存在一些问题,age 字段(根据您请求的输出)应该是 int,您需要记住在您的代码中声明 agename 的顺序构造函数。也可以用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
    

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 2023-04-11
      • 2019-12-08
      • 2018-12-09
      相关资源
      最近更新 更多