C++ exercises and solutions: Doubly Linked List search for item


C++ OOP: Doubly Linked List

Search item in doubly linked list


Step 6: Searching for an item in the doubly linked list

Another important operation of the doubly linked list is searching for an item. To search for a specific item in the doubly 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 doubly linked list


template <class Type>
ListElem<Type>  *LinkedList<Type>::find(int val){
          ListElem<Type> *tr;    
          tr=pfirst;
          if(pfirst!=NULL){
                   while(tr!=NULL){
                             if(tr->data==val) break; //found the tartget=>stop searching
                             else tr=tr->next;//otherwise continue searching
                             }
          }
              return tr;
}


Comments




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.