Search an element item in a Linked List

#include<bits/stdc++.h>

using namespace std;


struct Node

{

    int data;

    struct Node *Next;

};

int main()

{

    int arr[]= {1,2,3,4,5};

    struct Node *temp,*Head=NULL,*current=NULL;

    //insert data from array

    for(int i=0; i<5; i++)

    {

        temp= (struct Node *)malloc(sizeof(struct Node));

        temp->data=arr[i];

        temp->Next=NULL;

        if(Head==NULL)

        {

            Head=temp;

            current=temp;

        }

        else

        {

            //current=temp;

            current->Next=temp;

            current=current->Next;

        }

    }


    int sitem;

    // input search item

    cin>>sitem;

    int index=0;

    //searching happened here

    while(Head!=NULL)

    {


        if(sitem==Head->data){

            cout<<"data:"<<Head->data<<endl;

            cout<<"index:"<<index<<endl;

            break;

        }

        Head=Head->Next;

        index++;

    }


}


Comments