问:在双向链表的开头插入新节点的程序。

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

说明

在此程序中,我们将创建一个双向链表,并将每个新节点插入到列表的开头。如果列表为空,则 head 和 tail 都将指向新添加的节点。如果列表不为空,则将新节点插入到列表的开头,使得 head 的前驱指向新节点。将新节点设为列表的 head,其前驱指向 null。

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

考虑上面的例子。最初,1 是列表的 head。现在,将 new 插入到节点 1 之前,使得节点 1 的前驱指向 new。将 new 设为列表的 head,其前驱指向 null。

算法

  1. 定义一个 Node 类,它表示列表中的一个节点。它将有三个属性:数据、previous 指向前一个节点,以及 next 指向下一个节点。
  2. 定义另一个用于创建双向链表的类,它有两个节点:头节点和尾节点。最初,头节点和尾节点将指向 null。
  3. addAtStart() 将向列表开头添加一个节点
    1. 它首先检查头节点是否为 null,然后将节点作为头节点插入。
    2. 头节点和尾节点都将指向新添加的节点。
    3. 头节点的前一个指针将指向 null,尾节点的下一个指针将指向 null。
    4. 如果 head 不为 null,则 head 的前驱将指向新节点。
    5. 将新节点设为列表的 head。
    6. 由于新节点成为了 head,所以它的前驱应该指向 null。
  4. display() 将显示列表中存在的所有节点。
    1. 定义一个新节点“current”,它将指向头节点。
    2. 打印 current.data 直到 current 指向 null。
    3. 在每次迭代中,current 将指向列表中的下一个节点。

解决方案

Python

输出

Adding a node to the start of the list: 
1 
Adding a node to the start of the list: 
2 1 
Adding a node to the start of the list: 
3 2 1 
Adding a node to the start of the list: 
4 3 2 1 
Adding a node to the start of the list: 
5 4 3 2 1 

C

输出

Adding a node to the start of the list: 
1 
Adding a node to the start of the list: 
2 1 
Adding a node to the start of the list: 
3 2 1 
Adding a node to the start of the list: 
4 3 2 1 
Adding a node to the start of the list: 
5 4 3 2 1 

JAVA

输出

Adding a node to the start of the list: 
1 
Adding a node to the start of the list: 
2 1 
Adding a node to the start of the list: 
3 2 1 
Adding a node to the start of the list: 
4 3 2 1 
Adding a node to the start of the list: 
5 4 3 2 1 

C#

输出

Adding a node to the start of the list: 
1 
Adding a node to the start of the list: 
2 1 
Adding a node to the start of the list: 
3 2 1 
Adding a node to the start of the list: 
4 3 2 1 
Adding a node to the start of the list: 
5 4 3 2 1 

PHP

输出

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