Deletion operation in DLL is simpler when compared to SLL. Because we don't have to go in search of previous node of to-be-deleted node.
Here is how you delete a node
But we should always consider boundary conditions. What happens if we are trying to delete the first node or last node?
If first node is to be deleted, its previous node is NULL. Hence step 3 should not be used. And also, once head is deleted, nextnode becomes head.
Similarly if last node is to be deleted, nextnode is NULL. Hence step 4 is as strict NO NO. And we should set prevnode to tail.
After we put these things together, we have
You can download the complete program here.
Here is how you delete a node
- Link previous node of node of to-be-deleted to next node.
- Link next node of node of to-be-deleted to previous node.
- Free the memory of node of to-be-deleted
- prevnode = delnode->prev;
- nextnode = delnode->next;
- prevnode->next = nextnode;
- nextnode->prev = prevnode;
- free(delnode);
But we should always consider boundary conditions. What happens if we are trying to delete the first node or last node?
If first node is to be deleted, its previous node is NULL. Hence step 3 should not be used. And also, once head is deleted, nextnode becomes head.
Similarly if last node is to be deleted, nextnode is NULL. Hence step 4 is as strict NO NO. And we should set prevnode to tail.
After we put these things together, we have
- prevnode = delnode->prev;
- nextnode = delnode->next;
- if(prevnode) prevnode->next = nextnode;
- if(nextnode) nextnode->prev = prevnode;
- if(delnode==head) head = nextnode;
- if (delnode==tail) tail = prevnode;
- free(delnode);
void delete_node(NODEPTR*head, NODEPTR *tail,int value)
{
NODEPTR prevnode,nextnode;
NODEPTR delnode = find_node(*head,value);
if(delnode==NULL)
{
printf("NO such node..");
return;
}
prevnode = delnode->prev;
nextnode = delnode->next;
if(prevnode) //we have a previous node
prevnode->next = nextnode;
if(nextnode) //we have a next node
nextnode->prev = prevnode;
//if head is deleted, adjust head
if(delnode==*head)
*head = nextnode;
//if tail is deleted, adjust tail
if(delnode==*tail)
*tail = prevnode;
free(delnode);
}
You can download the complete program here.
Comments
Post a Comment