在循環(huán)單鏈表中搜索需要遍歷鏈表。要在鏈表中搜索的數(shù)據(jù)項(xiàng)與鏈表的每個節(jié)點(diǎn)數(shù)據(jù)匹配一次杏瞻,如果找到匹配符欠,則返回該數(shù)據(jù)項(xiàng)的位置嫡霞,否則返回-1
。
該算法在C語言中的實(shí)現(xiàn)給出如下希柿。
算法
第1步:設(shè)置PTR = HEAD
第2步:設(shè)置I = 0
第3步:如果PTR = NULL
提示 內(nèi)存溢出
轉(zhuǎn)到第8步
[IF結(jié)束]
第4步:如果IF HEAD → DATA = ITEM
寫入i + 1返回[結(jié)束]
第5步:重復(fù)第5步到第7步直到PTR-> next诊沪!= head
第6步:如果ptr→data = item
執(zhí)行 i + 1
返回
[IF結(jié)束]
第7步:I = I + 1
第8步:PTR = PTR→NEXT
[循環(huán)結(jié)束]
第9步:退出
示例代碼 -
#include<stdio.h>
#include<stdlib.h>
void create(int);
void search();
struct node
{
int data;
struct node *next;
};
struct node *head;
void main()
{
int choice, item, loc;
do
{
printf("\n1.Create\n2.Search\n3.Exit\n4.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));
struct node *temp;
if (ptr == NULL)
{
printf("OVERFLOW\n");
}
else
{
ptr->data = item;
if (head == NULL)
{
head = ptr;
ptr->next = head;
}
else
{
temp = head;
while (temp->next != head)
{
temp = temp->next;
}
temp->next = ptr;
ptr->next = head;
}
printf("Node Inserted\n");
}
}
void search()
{
struct node *ptr;
int item, i = 0, flag = 1;
ptr = head;
if (ptr == NULL)
{
printf("Empty List\n");
}
else
{
printf("Enter item which you want to search?\n");
scanf("%d", &item);
if (head->data == item)
{
printf("item found at location %d", i + 1);
flag = 0;
return;
}
else
{
while (ptr->next != head)
{
if (ptr->data == item)
{
printf("item found at location %d ", i + 1);
flag = 0;
return;
}
else
{
flag = 1;
}
i++;
ptr = ptr->next;
}
}
if (flag != 0)
{
printf("Item not found\n");
return;
}
}
}
執(zhí)行上面示例代碼,得到以下結(jié)果 -
1.Create
2.Search
3.Exit
4.Enter your choice?1
Enter the item
12
Node Inserted
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?2
Enter item which you want to search?
12
item found at location 1