单链表搜索

5 Sept 2024 | 2 分钟阅读

搜索是为了找到列表中特定元素的位置。搜索列表中的任何元素都需要遍历列表,并将列表中的每个元素与指定元素进行比较。如果元素与列表中的任何元素匹配,则从函数返回该元素的位置。

算法

  • 步骤 1: 设置 PTR = HEAD
  • 步骤 2: 设置 I = 0
  • 步骤 3: 如果 PTR = NULL
  •   写“列表为空”
      转到步骤 8
      IF 结束

  • 步骤 4: 重复步骤 5 到 7 直到 PTR != NULL
  • 步骤 5: 如果 ptr → data = item
  •   写 i+1
      IF 结束

  • 步骤 6: I = I + 1
  • 步骤 7: PTR = PTR → NEXT
  • [循环结束]

  • 步骤 8: 退出

C 函数

输出

1.Create
2.Search
3.Exit
4.Enter your choice?1

Enter the item
23

Node inserted

1.Create
2.Search
3.Exit
4.Enter your choice?1

Enter the item
34

Node inserted

1.Create
2.Search
3.Exit
4.Enter your choice?2

Enter item which you want to search?
34
item found at location 1

下一主题#