问:在双向链表中搜索元素程序

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

说明

在此程序中,我们需要在双向链表中搜索给定节点。

Program to search an element in a doubly linked list

要解决此问题,我们将使用一个名为 current 的节点遍历列表。Current 指向 head,并开始将要搜索的节点数据与当前节点数据进行比较。如果它们相等,则将标志设置为 true,并打印消息以及要搜索的节点的位置。

例如,在上表中,搜索节点 4 可以在位置 3 找到。

 

算法

  1. 定义一个 Node 类,它表示列表中的一个节点。它将有三个属性:数据、previous 指向前一个节点,以及 next 指向下一个节点。
  2. 定义另一个用于创建双向链表的类,它有两个节点:头节点和尾节点。最初,头节点和尾节点将指向 null。
  3. addNode() 将向列表中添加节点。
    1. 它首先检查头节点是否为 null,然后将节点作为头节点插入。
    2. 头节点和尾节点都将指向新添加的节点。
    3. 头节点的前一个指针将指向 null,尾节点的下一个指针将指向 null。
    4. 如果头节点不为 null,则新节点将插入到列表的末尾,使得新节点的前一个指针将指向尾节点。
    5. 新节点将成为新的尾节点。尾节点的下一个指针将指向 null。
  4. searchNode() 将在列表中搜索节点
    1. 变量 i 将跟踪要搜索节点的**位置**。
    2. 变量 flag 将存储布尔值 false。
    3. Current 将指向 head 节点。
    4. 通过将 current 递增到 current.next 并将 i 递增到 i + 1 来迭代循环。
    5. 将每个节点的数据与搜索的节点进行比较。如果找到匹配项,则将 flag 设置为 true。
    6. 如果 flag 为 true,则打印搜索节点的索引。
    7. 否则,打印消息“元素不在列表中”。

解决方案

Python

输出

Node is present in the list at the position : 3
Node is not present in the list

C

输出

Node is present in the list at the position : 3
Node is not present in the list

JAVA

输出

Node is present in the list at the position : 3
Node is not present in the list

C#

输出

Node is present in the list at the position : 3
Node is not present in the list

PHP

输出

Node is present in the list at the position : 3
Node is not present in the list
 
下一主题#