如何在链表的最后添加值。当我运行代码时,addAtLast() 方法不返回更新的列表。最后一个值(即 50)不会添加到返回的列表中。
public Node addAtLast(Node head, int data) {
Node temp = head;
Node newNode = new Node(data);
while (null != temp)
temp = temp.next;
temp = newNode;
System.out.println(temp);
return head;
}
……
最佳答案
这里:
temp = newNode;
您将新元素分配给一个从未与链接列表关联的temp
变量,因为分配对变量的引用会使其指向一个新事物。
此外,您需要的是停止迭代,因为当前元素没有下一个元素,而不是因为当前元素为 null
。否则,您不会保留引用最后一个元素的方法,而是 null
。
你应该写这样的内容:
while (temp.next != null)
temp = temp.next;
// here temp refers the last element of the chain as it doesn't have next element
temp.next = newNode;
关于java - 如何在链表的最后一个添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50535174/