-
Linked List Problem
I'm having a problem with a function for my linked list. What it does is navigate through a given number of nodes, seperates the list at that point, and then returns a pointer to the new head of the second list. If the end of the list is reached before the given number is reach, then it is supposed to return NULL. The function seems to work properly unless the end of the list is reached. I'm getting an exception if the list is shorter than the given number. I've tried a few different things and I don't understand what's causing it. NextNode is the List* for the list.
Code:
List* breakList(List* NodeHead, int NumNodes)
{
List* NewNodeHead;
while(NodeHead->NextNode && NumNodes)
{
NodeHead = NodeHead->NextNode;
NumNodes--;
}
NewNodeHead = NodeHead->NextMenuLine;
NodeHead->NextNode = NULL;
return NewNodeHead;
}
edit: Using text as test data I found I was losing 1 node each call. I've changed the return
-
You've helped me before so I'll help you now, I think I can cope... I'm newbie too.
There is a problem with the NumNodes variable, what if the argument passed were a valid list and -1? I always check whether list length is between 0 and list_size.
What is NextMenuLine exactly?
-
Problem fixed. I was calling the function with bad pointers. The list had already reached the end. Just need to add a check on the pointer before the while loop now.
-
NextMenuLine should have been NextNode. I simplified the code for posting purposes. Thanks on the -1 as that could also cause problems. Making it an unsigned it should fix that and probably cause a compiler error if used wrong
-
> I'm getting an exception if the list is shorter than the given number
Probably because your exit code should be surrounded with an if statement like
Code:
if ( NodeHead->NextNode == NULL ) {
return NULL;
} else {
// other stuff
}