11. Python 程序:在双向链表的末尾插入一个新节点。

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

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

Python program to insert a new node at the end of the Doubly Linked List

在上面的例子中,节点 4 是列表的 tail。 现在,新节点将被插入到列表的末尾,以便节点 4 的 next 将指向新节点。 将新节点作为列表的 tail,其 next 将指向 null。

算法

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

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

  • 定义一个新节点“current”,它将指向头节点。
  • 打印 current.data 直到 current 指向 null。
  • 在每次迭代中,current 将指向列表中的下一个节点。

程序

输出

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 
下一个主题Python 程序