在单链表中搜索元素的程序

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

说明

在此程序中,我们需要在给定的单链表中搜索一个节点。

Program to search an element in a singly linked list

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

例如,在上面的列表中,搜索的节点是4,可以在位置4找到。

算法

  1. 创建一个名为 Node 的类,它有两个属性:data 和 next。Next 是指向链表中下一个节点的指针。
  2. 创建另一个类SearchLinkedList,它有两个属性:head和tail。
  3. addNode() 将向列表添加一个新节点
    1. 创建一个新节点。
    2. 它首先检查 head 是否等于 null,这意味着列表为空。
    3. 如果列表为空,则 head 和 tail 都将指向新添加的节点。
    4. 如果列表不为空,新节点将添加到列表末尾,使得 tail 的 next 指向新添加的节点。此新节点将成为列表的新 tail。
  4. searchNode()将搜索列表中的一个节点
    1. 变量 i 将跟踪要搜索节点的**位置**。
    2. 变量 flag 将存储布尔值 false。
    3. Node current将指向head节点。
    4. 通过将 current 递增到 current.next 并将 i 递增到 i + 1 来迭代循环。
    5. 将每个节点的数据与搜索的节点进行比较。如果找到匹配项,则将 flag 设置为 true。
    6. 如果标志为true,则显示被搜索节点的所在位置。
    7. 否则,显示消息“元素不在列表中”。
  5. display() 将显示列表中存在的节点
    1. 定义一个节点current,它将最初指向列表的head。
    2. 遍历列表直到 current 指向 null。
    3. 通过使 current 在每次迭代中指向它的下一个节点来显示每个节点。

解决方案

Python

输出

Element is present in the list at the position : 2
Element is not present in the list

C

输出

Element is present in the list at the position : 2
Element is not present in the list

JAVA

输出

Element is present in the list at the position : 2
Element is not present in the list

C#

输出

Element is present in the list at the position : 2
Element is not present in the list

PHP

输出

Element is present in the list at the position : 2
Element is not present in the list
 
下一主题#