问:从双向链表中间删除新节点的程序。

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

说明

在此程序中,我们将创建一个双向链表并从列表的中间删除一个节点。如果列表为空,则显示消息“列表为空”。如果列表不为空,我们将计算列表的大小,然后将其除以 2 以获取列表的中间点。当前指针将指向头节点。我们将遍历列表直到到达中间点。现在当前指针将指向中间节点。我们删除中间节点,使其前一个节点指向当前节点的下一个节点。

Program to delete a new node from the middle of the doubly linked list

考虑上面的示例,上面列表的中间点是 3。从头节点到中间点迭代当前指针。现在,当前指针指向需要删除的中间节点。在这种情况下,节点 new 是需要删除的中间节点。可以通过使节点 2(当前节点的上一个节点)指向节点 3(当前节点的下一个节点)来删除 new。将当前指针设置为 null。

算法

  1. 定义一个 Node 类,它表示列表中的一个节点。它将有三个属性:数据、previous 指向前一个节点,以及 next 指向下一个节点。
  2. 为创建双向链表定义另一个类,它有两个节点:head 和 tail。最初,head 和 tail 将指向 null。
  3. deleteFromMid() 将从链表中删除中间节点
    1. 它首先检查 head 是否为 null(链表为空),然后,它将从函数返回,因为链表中没有节点。
    2. 如果列表不为空,它将检查列表是否只有一个节点。
    3. 如果链表包含多个节点,则它将计算链表的大小。将大小除以 2 并将其存储在变量 mid 中。
    4. 遍历列表直到当前指针指向列表的中间节点。
    5. 将当前节点的上一个节点连接到当前节点的下一个节点。
    6. 通过将 Current 设置为 null 来删除 Current 节点。
  4. display() 将显示列表中存在的所有节点。
    1. 定义一个新节点“current”,它将指向头节点。
    2. 打印 current.data 直到 current 指向 null。
    3. 在每次迭代中,current 将指向列表中的下一个节点。

解决方案

Python

输出

Original List: 
1 2 3 4 5 
Updated List: 
1 2 4 5 
Updated List: 
1 4 5 
Updated List: 
1 5 
Updated List: 
5 
Updated List: 
List is empty

C

输出

Original List: 
1 2 3 4 5 
Updated List: 
1 2 4 5 
Updated List: 
1 4 5 
Updated List: 
1 5 
Updated List: 
5 
Updated List: 
List is empty

JAVA

输出

Original List: 
1 2 3 4 5 
Updated List: 
1 2 4 5 
Updated List: 
1 4 5 
Updated List: 
1 5 
Updated List: 
5 
Updated List: 
List is empty

C#

输出

Original List: 
1 2 3 4 5 
Updated List: 
1 2 4 5 
Updated List: 
1 4 5 
Updated List: 
1 5 
Updated List: 
5 
Updated List: 
List is empty

PHP

输出

Original List: 
1 2 3 4 5 
Updated List: 
1 2 4 5 
Updated List: 
1 4 5 
Updated List: 
1 5 
Updated List: 
5 
Updated List: 
List is empty
 
下一主题#