Haythem Tarchouna
Haythem Tarchouna

Reputation: 17

Confusion about deleting the last node in linked list

The logic of deleting the last node is as follows right,

Go to the pointer of the node witch its next is NULL then free it, right? I tried to implement this logic in a function:

node* Delete_Last(node*head){
   node* i=head;
   while (i->next!=NULL){
      i=i->next;
   }
   free(i);
   i=NULL;
   return head;
}

When I try to print the list, I can't - it's an infinite loop. Can you tell what's the flaw in my logic and how to correct it, please?

Upvotes: 0

Views: 54

Answers (1)

Temple
Temple

Reputation: 1631

No its not right. You have to update previous node next node as well, and head if head was last node. So first of all you should take pointer to head pointer, you need that in case you need to update head. Secondly as it is singly linked list you should keep previous node:

node* Delete_Last(node** head) {
    if (!*head) {
        return 0;
    }

   node* i = *head, *previous = 0;
   while (i->next){
      previous = i;
      i = i->next;
   }
   free(i);
   if (previous) {
       previous->next = 0;
   } else {
       *head = 0;
   }
   return previous;
}

I don't know what you want to return, so I assumed on your code its new end, returning head again doesn't make sense. Now you can call this with:

node* prevLast = Delete_Last(&head);

Upvotes: 2

Related Questions