在单向链表开头插入新节点的程序

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

说明

在此程序中,我们将创建一个单链表,并在列表的开头添加一个新节点。要完成此任务,我们将头部存储到一个临时节点 temp 中。将新添加的节点设为列表的新头部。然后,将 temp(旧头部)添加到新头部之后。

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

考虑上面的列表;节点 1 代表原始列表的头部。设节点 New 为需要添加到列表开头的节点。节点 temp 将指向头部,即 1。将 New 设为列表的新头部,并将 temp 添加到新头部之后,使得 New 后面的节点为 1。

算法

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

解决方案

Python

输出

Adding nodes to the start of the list: 
1 
Adding nodes to the start of the list: 
2 1 
Adding nodes to the start of the list: 
3 2 1 
Adding nodes to the start of the list: 
4 3 2 1 

C

输出

Adding nodes to the start of the list: 
1 
Adding nodes to the start of the list: 
2 1 
Adding nodes to the start of the list: 
3 2 1 
Adding nodes to the start of the list: 
4 3 2 1 

JAVA

输出

Adding nodes to the start of the list: 
1 
Adding nodes to the start of the list: 
2 1 
Adding nodes to the start of the list: 
3 2 1 
Adding nodes to the start of the list: 
4 3 2 1 

C#

输出

Adding nodes to the start of the list: 
1 
Adding nodes to the start of the list: 
2 1 
Adding nodes to the start of the list: 
3 2 1 
Adding nodes to the start of the list: 
4 3 2 1 

PHP

输出

Adding nodes to the start of the list: 
1 
Adding nodes to the start of the list: 
2 1 
Adding nodes to the start of the list: 
3 2 1 
Adding nodes to the start of the list: 
4 3 2 1 
 
下一主题#