C++ exercises and solutions: search item


Circularly Linked List

Search item of circularly Linked List

Step 6: Searching for an item 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
}




Comments

Catlots comment

 Catlots

if it has two same data. How do you do it?


2017-01-10



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.