Algorithm to insert an element k in double linked list at a position which is:-
(i) Start of a linked list
while inserting at the start of the linked list we have to change the root node and so we need to return the new root to the calling program.
nodeptr insertatstart ( nodeptr root, nodeptr k)
{
k->next = root;
k->back = root->back;
root->back->next = k;
root->back=k;
return k;
}
(ii) After a given position p of list
Here we assume that p points to that node in the doubly linked list after which insertion is required.
insertafter ( nodeptr p , nodeptr k )
{
if (p == null)
{
printf (“void insertion /
return;
}
k->back = p;
k->next = p->next;
p->next->back =
k; p->next = k;
return;
}
(iii) End of linked list
Here k is the element to be inserted and root is the pointer to the first node of the doubly linked list.
insertatend ( nodeptr root, nodeptr k )
{
nodeptr trav;
while (trav->next != root)
trav = trav->next;
k->next=root;
root->back=k;
trav->next = k;
k->back=trav;
return;
}