Java中单链表查找元素位置_数据结构:单向链表系列5--在链表中查找元素

本文介绍了如何在Java和C#的单链表中查找元素,提供了迭代和递归两种方法。迭代法通过遍历链表,当找到目标元素时返回true,否则返回false。递归法则利用函数调用自身,依次检查每个节点直到找到目标元素或遍历完整个链表。
摘要由CSDN通过智能技术生成

在链表中查找元素

函数签名:

bool search(Node *head, int x)

如果在链表中查找到这个元素返回true,否则false

迭代法

2) 初始化一个节点指针, current = head.

3) 如果current不为NULL执行以下循环

a) current->key 等于当前待查找值key则返回true.

b) current = current->next

4) 否则返回 false

/*Checks whether the value key is present in linked list*/

bool search(struct Node* head, intkey)

{

struct Node* current = head; //Initialize current

while(current !=NULL)

{

if(current->data ==key)

return true;

current = current->next;

}

return false;

}

java:

//Checks whether the value key is present in linked list

public boolean search(Node head, intkey)

{

Node current = head; //Initialize current

while (current != null)<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值