user2067720
user2067720

Reputation:

Linked List Explanation

I am new to C, i am trying to learn linked lists, can some one explain me the code below. I understand some part of it but not all of it.

void deletefrombeginning( node **head, node **tail)
{
  node *temp;
  if(*head==NULL)
    return;
  temp=*head;
  if(*head==*tail) 
            *head=*tail=NULL;
  else
      {
          (temp->next)->prev=NULL;  <-- there is where i get lost.
          *head=temp->next;
       }
        free(temp);
}

Upvotes: 1

Views: 194

Answers (2)

Anish Ramaswamy
Anish Ramaswamy

Reputation: 2341


             ------              ------         
            |      | <--prev--- |      |
NULL <----- | temp |            | node | -----> ...
            |      | ---next--> |      |
             ------              ------

Short answer:

  • (temp->next)->prev=NULL; makes sure that node->prev doesn't access invalid memory.
  • *head=temp->next; makes temp the new head of the list.

Long answer:

  • You are currently at temp.
  • You cannot delete temp first because you then would have broken links (what would node->prev point to?).
  • This means you have to first remove the links related to temp.
  • Since temp is the first node, temp->prev should point to NULL.
  • So (temp->next)->prev=NULL; is equivalent to node->prev = NULL;.
  • We cannot directly do node->prev = NULL; because we do not know node exists at this point.
  • *head=temp->next makes sure that the new list head is node (in my above ascii demonstration).
  • The next step then frees the memory used by temp.

Tip: In case you're nitpicky like me, you might want to assign temp to NULL right after you free it. This makes sure that you can never mistakenly access temp in the rest of your code. Memory can still be accessed in error even after freeing it.

Upvotes: 0

Annika Peterson
Annika Peterson

Reputation: 260

(temp->next)->prev=NULL;

This line is making the prev pointer of what will be your new head NULL. So that when the second item in your linked list becomes the new head with:

*head = temp->next;

it has no prev pointer and is therefore the new head.

Upvotes: 1

Related Questions