﻿ C exercises and solutions: Search for element

C exercises and solutions: Search for element

Search for element in circularly linked list

Step 6: Searching for an element in the circularly linked list

Another important operation of the circularly linked list is searching for an item. To search for a specific item in the circularly linked list is a sequential process. The comparison starts from the beginning of the list until the target item is found or until the end of the list is reached. Therefore, the firs matched item is returned.

//Searching for an item in the circularly linked list ListElem *find(ListElem *L,int val){

ListElem *tr;
int f=0;
if(L!=NULL){

if(L->data==val) return L;//The target item is the first item
else{ //search the next item
tr=L->next;
while(tr!=L){
if(tr->data==val) {f=1;break;} //found the tartget=>stop searching
else tr=tr->next;//otherwise continue searching

}
}

if(f!=0) return tr; //return found item
else return NULL;//otherwise return NULL
}
else return NULL; //empty list
}