Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
First of, this question comes from my Assignment. In assignment 1 I was to use arrays to store information from 4 files into appropriate structs/classes.
In assignment 2 i need to do the same thing only using link-list this time.

The trouble is in Asg1 I searched for a particular info in File 1(say ID entered by user) and searched for relevant info using that ID in File 2(ID, name, age, etc).
Now using arrays to do is really simple, but how am I to do this using link-list. I understand the basic-moderate concepts of link-lists.

Any solution such as theory or codes would be appreciated.

What I have tried:

Google search on the concept of link-list. Couldn't find any relevant information.
Posted
Updated 22-Sep-18 13:01pm
v2

1 solution

To search a linked list you have to traverse the list. Here is a snippet of code that will traverse a list. It assumes the list pointer aims at the head of the list and there is a method to get a pointer to the next entry in the list.
C++
ListItem * p = pList;
while( p )
{
   // here you compare p's data to the item you are searching for

   p = p->Next();
}
Typically each entry of the list has a pointer to the next entry (the link) so the Next method would just return that or you could change it to assign the pointer to p. If your comparison finds a match then you have a pointer to the list item to use. A common thing to do is to make a search function to find a text string in the list. Here's an example of one where the ListItem has a pointer to a text string and the pointer to the next item is called pNext :
C++
ListItem * FindText( ListItem *pList, const char *txt )
{
    ListItem * p = pList;
    while( p )
    {
       if( strcmp( p->Text, txt ) == 0 )
           break;   // found it so stop traversing the list
       p = p->pNext;
    }
    return p;  // points to item with matching text or null if none
}
 
Share this answer
 
v2
Comments
Member 13994200 23-Sep-18 1:40am    
OK i think I have get it. Thanks!
Maciej Los 23-Sep-18 6:02am    
Good job!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900