【问题标题】:Why does adding a new node to front of linked list NOT work in my code?为什么在我的代码中将新节点添加到链表的前面不起作用?
【发布时间】:2023-04-11 07:08:01
【问题描述】:

为什么我不能在我的链表中插入一个新节点,如下所示?我的 insertNodeToHead 仅在我的返回类型是 Node 本身并且我返回 root 时才有效。但我希望能够在不返回任何内容的情况下更改链接列表本身。目前,它应该打印 0,1,2,3,4,但只打印 1,2,3,4。

这是我的代码:

// Create a singly linked list class
public class Node {
    int data;
    Node next = null;

    public Node (int age) {
        data = age;
    }

    // insert a node to the head of a linked list
    public void insertNodeToHead (Node n) {
        Node root = this;
        n.next = root;
        root = n;
        return;

    }


    public static void main(String[] args) {
        Node root = new Node(1);
        root.next = new Node(2);
        root.next.next = new Node(3);
        root.next.next.next = new Node(4);

        // insert new node
        Node insertNew = new Node(0);
        root.insertNodeToHead(insertNew);

        Node current = root;
        while (current != null) {
            System.out.println(current.data); 
            current = current.next;
        }
    }
}

【问题讨论】:

  • 您能解释一下您的insertNodeToHead 方法的作用吗,具体来说
  • 假设我的链表是 1->2->3->4。现在如果我想将新节点(0)添加到这个列表中,我的新列表应该是 0->1->2->3->4
  • 我不是在问它应该做什么,我是在问它做什么。引导我们完成它。
  • 哦,对不起。因此,首先它为节点的当前实例创建一个变量“root”。然后要添加的新节点“n”指向根,然后“n”成为根本身。但是,实例不会改变。我不能做“this = root”,因为 java 给我一个错误,说赋值的左侧必须是一个变量本身”。我想改变实例本身。

标签: java linked-list singly-linked-list


【解决方案1】:

您的this 表示此节点:Node root = new Node(1); 您想要在insertNodeToHead 方法中设置this = n,但是如果使用void 方法,则无法使this 指向另一个节点. Ravi Thapliyal 的回答已经解释了这一点。

一个解决方案是 Ravi Thapliyal 的建议,它使用另一个类来保存对根节点的引用。如果您不想引入新类,建议使用返回Node 类型的方法来满足您的要求:

public class Node {
    int data;
    Node next = null;

    public Node (int age) {
        data = age;
    }

    // insert a node to the head of a linked list and return the head
    public Node insertNodeToHead(Node n) {
        n.next = this;
        return n;
    }


    public static void main(String[] args) {
        Node root = new Node(1);
        root.next = new Node(2);
        root.next.next = new Node(3);
        root.next.next.next = new Node(4);

        // insert new node
        Node insertNew = new Node(0);
        Node current = root.insertNodeToHead(insertNew);

        while (current != null) {
            System.out.println(current.data); 
            current = current.next;
        }
    }
}

【讨论】:

    【解决方案2】:

    好吧,您的所有insertNodeToHead() 方法所做的就是将当前的root 节点附加为next 节点的insertNew 节点。执行 root = n; 在方法之外没有任何影响,因为它只是一个 local 变量。

    现在,从技术上讲,新节点已成为列表的根,但您看不到它,因为您仍在从旧的 root 节点迭代列表,即从现在具有 @ 的列表的第二个节点987654327@在头。

    您需要引入另一个类,例如SinglyLinkedList 或其他类,它包含对根节点的引用并为您操作列表。您不应该将此逻辑添加到您的 Node 类本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      • 2020-09-29
      相关资源
      最近更新 更多