Java 在单链表末尾插入新节点的程序

2025年3月17日 | 阅读 3 分钟

在此程序中,我们将创建一个单链表并在列表末尾添加一个新节点。要完成此任务,请在列表的尾节点之后添加一个新节点,以便尾节点的 next 指向新添加的节点。然后,将此新节点设为列表的新尾节点。

Java program to insert a new node at the end of the singly linked list

考虑上面的列表;节点 4 代表原始列表的尾节点。设节点 New 是需要添加到列表末尾的新节点。使 4 的 next 指向 New。使 New 成为列表的新尾节点。

算法

  • 创建一个名为 Node 的类,它有两个属性:data 和 next。Next 是指向链表中下一个节点的指针。
  • 创建另一个名为 InsertEnd 的类,它有两个属性:head 和 tail。
  • addAtEnd() 将在列表末尾添加一个新节点
    • 创建一个新节点。
    • 它首先检查 head 是否等于 null,这意味着列表为空。
    • 如果列表为空,则 head 和 tail 都将指向新添加的节点。
    • 如果列表不为空,新节点将添加到列表末尾,使得 tail 的 next 指向新添加的节点。此新节点将成为列表的新 tail。

a. display() 将显示列表中存在的节点

  • 定义一个节点 current,它最初将指向列表的 head。
  • 遍历列表直到 current 指向 null。
  • 通过使 current 在每次迭代中指向它的下一个节点来显示每个节点。

程序

输出

Adding nodes to the end of the list: 
1 
Adding nodes to the end of the list: 
1 2 
Adding nodes to the end of the list: 
1 2 3 
Adding nodes to the end of the list: 
1 2 3 4 
下一个主题Java 程序