Node* deleteAtTail(Node* head)
{
if (head == NULL) /* If List is empty... */
{
return NULL;
}
else /* If List has 1 item... */
if (head -> next == NULL)
{
free(head);
return NULL;
}
else
{
Node* currentNode = head; /* Traversal Pointer */
Node* previousNode = NULL; /* Traversal Pointer */
while(currentNode -> next != NULL)
{
previousNode = currentNode; /* Move up previous node */
currentNode = currentNode -> next; /* Move up current node */
}
previousNode -> next = NULL; /* Make previousNode the new tail */
free(currentNode); /* Delete currentNode pointer */
return head;
}
}
If I remove/comment out previousNode -> next = NULL;, the program falls into an infinite loop.
Why is this the case? It seems to me that head and its list is unchanged, only copied to the currentNode pointer, and I am returning an unchanged list. previousNode and currentNode stay within the scope of the function, so why is it that the program fails if previousNode's next pointer is not set to NULL?
deleteAtTailis called, and then the list had been corrupted by the error indeleteAtTail. While your reasoning thatpreviousNodeandcurrentNodeexist only during the function’s execution, they are only pointers to nodes that exist in the list beyond the function’s execution. You must handle those nodes correctly.