Program for sorted insertion in linked list
Write a function to insert a node in linked list as sorted manner. For example if linked list is 3->5->23->45->65 and we want to insert a node in which data is 22 then insert it at its correct position which is between 5 and 23.
C Program:
C Program:
#include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node *next; }; /* Function to create new node for inserting in linked list. This function take an integer as argument and return a node in which data is that integer. */ struct Node *CreateNode(int n) { struct Node *newNode=(struct Node*)malloc(sizeof(struct Node)); newNode->data = n; newNode->next = NULL; return newNode; } struct Node *InsertSort(struct Node *head,struct Node *newNode) { struct Node *temp = head; /* If there is no node in linked list or data in new node is less than or equal to data in head node then insert it at the first position */ if(head==NULL||head->data>=newNode->data) { newNode->next = head; head = newNode; } else { /* If data in new node is greater than head node then find an appropriate place to insert node in linked list */ while(temp->next!=NULL&&temp->next->data<newNode->data) { temp = temp->next; } newNode->next = temp->next; temp->next = newNode; } return head; } void PrintList(struct Node *head) { struct Node *curr = head; if(curr==NULL) { printf("List is empty"); } else { while(curr!=NULL) { printf("%d ",curr->data); curr = curr->next; } } printf("\n"); } int main() { struct Node *head = NULL; struct Node *newNode = CreateNode(5); head = InsertSort(head,newNode); newNode = CreateNode(7); head = InsertSort(head,newNode); PrintList(head); newNode = CreateNode(3); head = InsertSort(head,newNode); PrintList(head); return 0; }