having hard time debugging deletion of head node in a circular linked list

135 Views Asked by At

I'm learning data structures and was practicing questions on circular linked list. So, i'm supposed to write a function which deletes the head node of a circular linked list, so i came up with this code -

void del_head(struct node** head, struct node** tail)
{
    struct node* new_head = (*head)->next;
    free(*head);
    *head = new_head;
    (*tail)->next = *head;
}

After debugging i found that the tail is not getting updated.

I'm having tough time trying to find the problem.

Any help is appreciated, thanks

1

There are 1 best solutions below

1
On

After debugging i found that the tail is not getting updated.

Your code will work perfectly fine for a circular list having more than 1 node and since you are deleting head node, so if the list will have more than 1 node, tail will be pointing to same node after head node deletion as it was pointing to a node before deletion.

Consider a case where the circular list has only one node:

      head---+      
             |
   tail----+ |
           | |
          ---------------
          | data | next |-------+
          ---------------       |
             |                  |
             +------------------+

head, tail and node next all are pointing to same node.
For this scenario, your code will end up accessing a deallocated memory.

You can do:

void del_head(struct Node** head, struct Node** tail) {

    // validate head and tail pointer
    if (!(head && *head)) {
        printf ("Invalid head pointer\n");
        return;
    }

    if (!(tail && *tail)) {
        printf ("Invalid tail pointer\n");
        return;
    }

    struct Node* x = *head;
    if (*tail == x) {
        // the circular list has only one node
        *head = *tail = NULL;
    } else {
        *head = (*tail)->next = x->next;
    }

    x->next = NULL;
    free(x);
}