randomuser
randomuser

Reputation: 298

Deleting elements in linked list

This appeared on one of the old exams on algorithms and data structure. It seems pretty simple but I need some help with understanding why it works.

The goal is to delete certain atoms from a singly linked list using only a pointer to head.

The structure of atom is:

struct at {
 int element;
 struct at *next;
};
typedef struct at atom;

The solution is:

void delete(atom **head)
{
  while((*head)){
    if((*head)->element%2){ /*just a condition for deleting*/
      (*head)=(*head)->next; /*deleting the atom*/
    } else {
       head= &(*head)->next; 
    }
   }
 }

What I understand is that, in this function, "*head" is the actual head (pointer to the first atom) and "head" is a pointer to the actual head. Clearly, since I'll actually change the head and contents of the list, I need to pass a pointer to head.

I just can't understand how head= &(*head)->next seems to work. I've tried putting it down on paper and still can't make any sense of it. How does it not change anything and just jump to the next atom?

Upvotes: 1

Views: 62

Answers (1)

Monk
Monk

Reputation: 786

As you said *head is the actual head (pointer to the first atom) and head is a pointer to the actual head.In statement head= &(*head)->next; we are updating head (which contains address of the actual head) with the address of address of node next to actual head node.

Now head is a pointer which store the address of head to next node not head node i.e next atom.

Consider a list 1->2->3->4->5

in this case initially head contains the address node 1, and *head is node 1 itself. Now when we say head= &(*head)->next; it means head will store address of node 2.If we will do *head it return node 2.

Upvotes: 1

Related Questions