Reputation: 45
Good evening. I've encountered the following problem while trying to understand linked lists logic. I'm using this function, to remove a node from linked list.
void removeNode(ListNode* after)
{
ListNode* toDelete;
toDelete = after->next;
after->next = toDelete->next;
free(toDelete);
}
This is how I call the function:
while (temp2 != NULL)
{
if (temp3 == lst.head && temp3->dataPtr[0] >= '0' && temp3->dataPtr[0] <= '9')
{
lst.head = temp3->next;
ListNode* temp4 = temp3;
temp3 = temp3->next;
free(temp4);
temp2 = temp2->next;
}
if (temp2->dataPtr[0] >= '0' && temp2->dataPtr[0] <= '9')
{
if (temp2 == lst.head)
{
lst.head = temp2->next;
ListNode* temp3 = temp2;
temp2 = temp2->next;
free(temp3);
}
else
{
-----------------> removeNode(temp3);
temp2 = temp2->next;
temp3 = temp3->next;
}
}
else
{
temp2 = temp2->next;
temp3 = temp3->next;
}
}
The problem that I encounter: After using removeNode function, I can't access the nodes anymore!
Can anyone spot my mistake and correct me? I'm trying for about two hours to solve this, but can't think of any possible mistake I've written. The rest of the program is working well, all the other 'else' or 'if's', its just this specific line that doesn't work.
Big thanks in advance.
Upvotes: 0
Views: 56
Reputation: 45
Thank you for your reply, user3777427. I've updated the marked line (at the 1st message), to the following, and it worked.
temp2 = temp2->next;
ListNode* toDelete;
toDelete = temp3->next;
temp3->next = temp3->next->next;
free(toDelete);
Upvotes: 0
Reputation: 41
There seems to be an error in the removeNode function. As far as I see, you are trying to remove the node that comes after the given node in the function argument. The line:
after-> next = after-> next;
needs to be replaced with:
after->next = (after->next)->next;
to be able to remove the connection to the node to be deleted.
Upvotes: 2