java - 如何在链表的最后一个添加值

标签 java linked-list

如何在链表的最后添加值。当我运行代码时,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/

相关文章:

java - 选项卡 fragment 不起作用?

java - Netty上的FileInputStream是什么

java - 在 Facebook 上发布图片不起作用

将字符串转换为链接列表

python - 如何在Python中创建链表

java - 为基于套接字的 Android 应用程序创建非卡住 UI 的理想方式

java - Libgdx 中的简单 OpenGL ES 着色器输出是白色应该是红色

c - 遍历ifaddr的链表

java - 使用带有链表的冒泡排序

c - 用 C 语言编写一个程序,使用 rand() 函数创建 1000 个结构体