Algorithm to insert a node in circular linked list
Algorithm to insert a node in circular linked list
1. Allocate the space for the new node and store data into the data part of the node and store
NULL at the address part of the node.
NewNode->next=NULL
2. We need to declare a temporary pointer temp in order to traverse through the list. Temp is
made to point to the first node of the list.
temp = ptr
3. Then, traverse through the entire linked list
while (temp→ next != ptr)
temp = temp → next;
4. At the end of the loop, the temp will be pointing to the last node of the list. We need to make
the next part of the temp node (which is currently the last node of the list) point to the new
node (ptr).
temp = ptr;
while (temp -> next != ptr)
{
temp = temp -> next;
}
temp->next = NewNode;
NewNode->next=ptr;
Algorithm:
Step 1: IF PTR= NULL Write OVERFLOW
Go to Step 1
[END OF IF]
Step 2: SET NEW_NODE = PTR
Step 3: SET PTR = PTR - > NEXT
Step 4: SET NEW_NODE - > DATA = VAL
Step 5: SET NEW_NODE - > NEXT = NULL
Step 6: SET PTR = HEAD
Step 7: Repeat Step 8 while PTR - > NEXT != PTR
Step 8: SET PTR = PTR - > NEXT
[END OF LOOP]
Step 9: SET PTR - > NEXT = NEW_NODE
Step 10: SET NEW_NODE->NEXT=PTR
Step 10: EXIT
Inserting a new element into a circular linked list at the beginning is quite simple. We just need
to make a few adjustments in the node links. There are the following steps that need to be
followed in order to insert a new node in the list at the beginning.
1. Allocate the space for the new node and store data into the data part of the node and store
NULL at the address part of the node.
NewNode->next=NULL
2. We need to declare a temporary pointer temp in order to traverse through the list. Temp is
made to point to the first node of the list.
temp = ptr
3. Then, traverse through the entire linked list
while (temp→ next != ptr)
temp = temp → next;
4. At the end of the loop, the temp will be pointing to the last node of the list. We need to make
the next part of the temp node (which is currently the last node of the list) point to the new
node (ptr).
temp = ptr;
while (temp -> next != ptr)
{
temp = temp -> next;
}
NewNode->next=ptr;
ptr=NewNode;
temp->next=NewNode;