node *head, *current, *temp;
current = head;
while(NULL != current){
temp = current;
current = current->next;
}
delete current;
current = temp;
current->next = NULL;
I’m just wondering I know there’s something like this and there’s recursion, assuming there’s already a linked list and we don’t know how many nodes are in the list.
By delete I mean deallocate.
node *head, *current, *temp;
current = head;
while(NULL != current->next){
temp = current;
current = current->next;
}
if (NULL != current){
delete current;
current = temp;
current->next = NULL;
}
Your code does not do anything: the exit condition of the loop is
NULL == current, meaning thatdelete current;will always passNULLtodelete. This is OK, but it does not de-allocate anything.You should change your loop to stop when
current->next == NULL, but you must be extra careful to make sure that you do not dereferencecurrentwhen it is equal toNULL:EDIT : Your edited code mimics my answer to a large extent, except yours would fail if
head == NULL. It would also fail if the list has exactly one node, becausetempwould remain unassigned.