Professional Documents
Culture Documents
1. Head of list
2. Tail of list
3. Before a given node
4. After a given node
To insert a node at head, make sure that head pointer is change after insertion. Also in DLL,
previous pointer of last head node points to new node, next of new node points to last head node
and previous of new node points to NULL. Below these steps are clarified:
To insert at end, we obviously need to traverse to end of list. There is special case that needs to
be handle, that is if this is first node of doubly linked list. Extra thing to do is point previous of
first node to NULL.
1. Create new node with data
2. Check if this is first node, make previous to point to NULL, change
headRef
3. Else traverse till last node of list.
4. Make next of last node point to new node.
5. Make previous of new node point to last node.
6. Make next of new node point to NULL
This is very similar case to insert at the end. Only thing not to be done is to check if this is first
node.Rest all remains same.
Again similar case to 3, only next and previous pointers to point to correct nodes.
In last few posts, we discussed about singly and doubly linked lists. This post is about circular
linked list. Singly linked list is a list where each node points to its next node, there is no link
from a node to previous, last node points to NULL node. Additional pointer needs to be kept in
order to traverse linked list from start. Example of singly linked list given below:
How to find what is head node of circular linked list? There are two ways :
1.Keeping an external pointer as in case of singly linked list, which points to head node.
2. Keeping a dummy node, header. This node is separated from regular nodes of list by keeping a
SENTINEL value in it. Other way is to have a flag to indicate that it is a head node.
We have an extra pointer which points to head node of the list. When node is added at front of
list, that pointer is to be changed. Also, in circular linked list, last node points to head node,
hence that link also should be changed.
Since head node is changing, function call will be headRef and not head pointer only. Below is
code for above algorithm to add a node at start of circular linked list
This insertion is same as singly linked list, as there is no change in head or tail of circular list.
Just scan to the required position, add new node.
next = prev->next;
prev->next = newNode;
newNode->next = next;
To remove a node, care should be taken when removing head or last nodes. When last node is
removed, previous to last node should now start pointing to head node. When head node is
removed, last node should now be pointing to new head node. Below is code to remove node.