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

2025年03月17日 | 阅读 9 分钟

说明

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

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

在上面的例子中,节点 4 是链表的尾部。现在,新节点将插入到链表的末尾,使得节点 4 的 next 指向新节点。将新节点设为链表的尾部,并使其 next 指向 null。

算法

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

解决方案

Python

输出

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

C

输出

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

JAVA

输出

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

C#

输出

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

PHP

输出

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