Do you know How to insert the node in a sorted linked list in c programming? If you don’t have a clear understanding of c language, to perform the task appropriately can be actually hard. Before knowing how to insert node in a sorted linked list you have first to know and understand what the linked list is
What is the linked list?
Linked list is held by use of a pointer known as local pointer variable which usually points to the first member of the list.
For the Null pointer, the list is termed as empty
How to insert node in a sorted linked list in c programming
After knowing what is a linked list then let us see How to insert node in a sorted linked list in c programming though you have to keep in mind that, the task is based on the definition of the struct that is done in a recursive manner
1. Perform basic linked list operation
You have to perform the basic linked list operation in order to insert a node in the sorted linked list
2. Insert a node in a sorted Linked List after basic linked list operation.
Then after performing the basic linked list operation, you have gone for your final task; the inserting of the node in the sorted linked list. Take after the below algorithm to do so.
- Make the node as head and you have to return it if given that the linked list is empty
- For the smaller value of the node to be inserted than the value of head node you have to insert the node at start as well as make it head
- search the right node
- Insert your node and you will completed your objective
void insert(struct node** head, struct node* myNode) { struct node* current; current = *head; while (current->next!=NULL && current->next->data < myNode->data) { current = current->next; } myNode->next = current->next; current->next = myNode; } }
Final note
The above algorithm may be challenging but start and follow one to next and you will find it working.enjoy c programming.