在迴圈單鏈表中搜索

在迴圈單鏈表中搜索需要遍曆鏈表。要在鏈表中搜索的資料項目與鏈表的每個節點數據匹配一次,如果找到匹配,則返回該資料項目的位置,否則返回-1

該演算法在C語言中的實現給出如下。

演算法

第1步:設置PTR = HEAD
第2步:設置I = 0
第3步:如果PTR = NULL
    提示 記憶體溢出

    轉到第8步

    [IF結束]

第4步:如果IF HEAD → DATA = ITEM
    寫入i + 1返回[結束]
第5步:重複第5步到第7步直到PTR-> next!= head
第6步:如果ptr→data = item
    執行 i + 1
        返回
    [IF結束]
第7步:I = I + 1
第8步:PTR = PTR→NEXT
[迴圈結束]

第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;
        }
    }

}

執行上面示例代碼,得到以下結果 -

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

上一篇: 迴圈單向鏈表 下一篇: 迴圈雙向鏈表