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

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

说明

在此程序中,我们将创建一个单链表并在列表末尾添加一个新节点。为此,请在列表的尾部添加一个新节点,使尾部的 next 指向新添加的节点。然后,将此新节点设置为列表的新尾部。

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

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

算法

  1. 创建一个名为 Node 的类,它有两个属性:data 和 next。Next 是指向链表中下一个节点的指针。
  2. 创建另一个名为 InsertEnd 的类,它有两个属性:head 和 tail。
  3. addAtEnd() 将在列表末尾添加一个新节点
    1. 创建一个新节点。
    2. 它首先检查 head 是否等于 null,这意味着列表为空。
    3. 如果列表为空,则 head 和 tail 都将指向新添加的节点。
    4. 如果列表不为空,新节点将添加到列表末尾,使得 tail 的 next 指向新添加的节点。此新节点将成为列表的新 tail。
  4. display() 将显示列表中存在的节点
    1. 定义一个节点 current,它最初将指向列表的 head。
    2. 遍历列表直到 current 指向 null。
    3. 通过使 current 在每次迭代中指向它的下一个节点来显示每个节点。

解决方案

Python

输出

 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 

C

输出

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

输出

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 

C#

输出

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 

PHP

输出

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 
 
下一主题#