執行搜索以便在鏈表中找到指定元素的位置。 搜索鏈表中的任何元素都需要遍曆列表,並將列表的每個元素與指定的元素進行比較。 如果元素與任何鏈表中的元素匹配,則從函數返回元素的位置。
演算法
第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<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("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