使用 Java 将节点附加到尾部

Appending a node to end of tail with Java

我正在研究一个基本的 Hackerrank 问题,我们将一个元素附加到链表的末尾。

/*
  Insert Node at the end of a linked list 
  head pointer input could be NULL as well for empty list
  Node is defined as 
  class Node {
     int data;
     Node next;
  }
*/
Node Insert(Node head,int data) {
    if(head == null) {
        Node node = new Node();
        head = node;
        head.data = data;
        head.next = null;
        return head;
    }

    while(head != null) {
        head = head.next;
    }

    head.data = data;
    head.next = null;
    return head;
}

出于某种原因,此解决方案无法编译。我在看其他人解决的问题,他们在非空链表解决方案中使用了一个临时节点。

您还需要在最后创建一个新节点。

此外,不要等到“head==null”,否则您将到达列表的末尾,您将不知道在何处插入节点。

您需要一直走到“head.next==null”,这样您才能到达当前的最后一个节点。

此外,如果您必须始终 return 列表的头部,您应该在开始迭代之前复制引用,如评论中所述。

Node Insert(Node head,int data) {
    if(head == null) {
       Node node = new Node();
       head = node;
       head.data = data;
       head.next = null;
       return head;
    }

    Node current = head;

    while(current.next != null) {
        current = current.next;
    }

    Node node = new Node();
    node.data = data;
    node.next = null;

    current.next = node;

    return head;
}