问。在循环链表中搜索元素的程序。

2025年1月8日 | 7 分钟阅读

说明

在此程序中,我们创建一个循环链表并在列表中搜索一个节点。

9->5->2->7->3

考虑上面的例子。假设我们需要搜索节点 5。为了解决这个问题,我们将遍历列表并将每个节点与 5 进行比较。如果找到匹配项,我们将标志设置为 true 并打印节点 5 的位置。在此示例中,节点 5 出现在位置 2。

算法

  1. 定义一个 Node 类,它表示列表中的一个节点。它有两个属性 data 和 next,next 将指向下一个节点。
  2. 定义另一个类来创建循环链表,它有两个节点:head 和 tail。
  3. search() 函数将搜索列表中的一个节点
    1. 变量 i 将跟踪要搜索节点的**位置**。
    2. 变量 flag 将存储布尔值 false。
    3. Current 将指向 head 节点。
    4. 通过将 current 递增到 current.next 并将 i 递增到 i + 1 来迭代循环。
    5. 将每个节点的数据与要搜索的节点进行比较。如果找到匹配项,则将 flag 设置为 true。
    6. 如果 flag 为 true,则打印搜索节点的 {position}。
    7. 否则,打印消息“元素不在列表中”。

解决方案

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
 
下一主题#