Bloggs Bloggs - 1 month ago 16
C++ Question

Attempted insert node leads to infinite linked list

I am trying to insert a node into a linked list after it finds a name in the list.
My problem is that when i print out the linked list it prints the nodes up to and including the node containing the name but then outputs infinitely the node I inserted. Any help would be greatly appreciated. Thanks!

(some extra information),(the pointer student is pointing to a dynamically created node already). :)

bool StudentLinkedList::insertStudentAfter(StudentNode* student, string _name)
{
StudentNode* curr = headP;
StudentNode* prev = headP;
while (curr != NULL)
{
if (curr->getName() == _name)
{


StudentNode* dummy = curr -> getnext();

curr->setNext(student);
prev = prev->getnext();

curr=curr ->getnext();
curr->setNext(dummy);

prev = curr;
curr = curr->getnext();


length++;
return true;
}
prev = curr;
curr = curr->getnext();
}
return false;


}

Answer

You have to simply insert your new node between curr & prev

If you really want to appreciate accept and upvote the answer

bool StudentLinkedList::insertStudentAfter(StudentNode* student, string _name) 
{ 
StudentNode* curr = headP;
StudentNode* prev = headP; 
while (curr != NULL) 
{ 
if (curr->getName() == _name)
{ 
student->setNext(curr->getnext()); 
curr->setNext(student); 
length++; 
return true;
} 
prev = curr; 
curr = curr->getnext(); 
} 
return false;
}