python 单链表查找元素_在单链表中搜索

本文介绍如何在Python中实现单链表的元素搜索。通过遍历链表,逐个比较元素,找到指定元素的位置。算法包括设置指针、初始化计数、循环遍历链表,直到找到匹配项或遍历完成。文中还提供了C语言的示例代码作为参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

算法

第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语言示例代码 -

#include

#include

void create(int);

void search();

struct node

{

int data;

struct node *next;

};

struct node *head;

void main()

{

int choice, item, loc;

do

{

printf("1.Create\n");

printf("2.Search\n");

printf("3.Exit\n");

printf("4.Enter your choice ? ");

scanf("%d", &choice);

switch (choice)

{

case 1:

printf("Enter the item\n");

scanf("%d", &item);

create(item);

break;

case 2:

search();

case 3:

exit(0);

break;

default:

printf("Please enter valid choice\n");

}

} while (choice != 3);

}

void create(int item)

{

struct node *ptr = (struct node *)malloc(sizeof(struct node *));

if (ptr == NULL)

{

printf("OVERFLOW\n");

}

else

{

ptr->data = item;

ptr->next = head;

head = ptr;

printf("Node inserted\n");

}

}

void search()

{

struct node *ptr;

int item, i = 0, flag;

ptr = head;

if (ptr == NULL)

{

printf("Empty List\n");

}

else

{

printf("Enter item which you want to search?\n");

scanf("%d", &item);

while (ptr != NULL)

{

if (ptr->data == item)

{

printf("item found at location %d ", i + 1);

flag = 0;

}

else

{

flag = 1;

}

i++;

ptr = ptr->next;

}

if (flag == 1)

{

printf("Item not found\n");

}

}

}

执行上面示例代码,得到以下结果 -

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

¥ 我要打赏

纠错/补充

收藏

上一篇:链表

下一篇:双链表

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值