I know questions about reversing linked lists have been asked before but I want to try to figure this out with my own implementation.
My code makes sense to me and I feel it should work but when I run the debugger, the loop runs infinitely. Specifically, head and next keep alternating between the first and second nodes of the linked list. The getLink() method returns the pointer of the node (which is pointing to the next node in the list). Any input based on my comments in under the while loop would help.
void revNodes(IntNodePtr& head)
{
IntNodePtr prev = NULL;
IntNodePtr next = NULL;
next = head;
while (next != NULL)
{
prev = head;
// this should advance the pointer head to the next node in the list because next is the same as head initially
head = next->getLink();
// advance the pointer next to node after it
next = next->getLink();
// set the pointer in the node that head is pointing to to prev (head before head was advanced)
head->setLink(prev);
}
}
You initialise
nexttoheadand then inside the loop you’re setting them to both point to the same node.Effectively, they’re both pointing at the first node after the head of the list, you’re then setting the pointer on that node to be the head of the list with the line
head->setLink(prev). Therefore, on your next pass through the loop,headandnextboth get pointed back at the original head node!If you change:
to:
You’ll be able to progress through the list, but then you’ll jump the next node as you set
headtonext->getLink(). So at the start you should initialisenextto behead->getLink(), setheadtonextinside the loop, andnexttohead->getLink()as above.So turning that into code: