Reputation:
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
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:
temp
.temp
first because you then would have broken links (what would node->prev
point to?).temp
. temp
is the first node, temp->prev
should point to NULL
.(temp->next)->prev=NULL;
is equivalent to node->prev = NULL;
.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).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
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