Search function not properly working

Hey ya'll, I'm having an issue with my search function, which is supposed to search a linked list for a value the user enters. I seem to have trouble with my loop termination.

Here's the function any hints will help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void ColorsList::searchList(string color)
{
    ListNode *currentNode = head;
    
    int position=0;
    
    while(currentNode != nullptr)
    {
       if(currentNode->colorType == color)
       {
           cout<<"Matched "<<currentNode->colorType<< " at position "<< position<<endl;
           //currentNode = currentNode->next;
           
       }
       else
       {
           position += 1;
           currentNode = currentNode->next;
       }
       
    }
    cout<<"No matching colors for "<<color<<endl;
    
}
Last edited on
I keep hitting an endless loop so I believe it the while loop doesn't terminate when it's supposed to. I know it has something to do with the currentNode->next, but I have yet to wrap my head around the whole linked list concept.
Briefly: The linked list is a series of nodes, where each node connects to the next node.
At the very end of the linked list, the currentNode->next will be nullptr.

As your code currently is, if line 9 is true, then it will be true forever, because the else branch will never be hit again.

Make sure that each node is being created correctly such that the node->next member is nullptr unless assigned to be another node pointer.

Since you found the matching color, you can simply replace line 12 with "return;".
Last edited on
An alternative could be (not tried):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void ColorsList::searchList(const string& color)
{
	int position = 0;
	ListNode* currentNode = head;

	while (currentNode != nullptr && currentNode->colorType != color)
	{
		++position;
		currentNode = currentNode->next;
	}

	if (currentNode != nullptr)
		cout << "Matched " << color << " at position " << position << endl;
	else
		cout << "No matching colors for " << color << endl;
}

Topic archived. No new replies allowed.