Sorted Linked List is a linked list where the elements are always sorted. Insert operation in a singly is bit tricky. You have to insert an element such a way that the list remains sorted after insertion. The insertion logic is:
- If the list is empty or the value of the element (to be inserted) is less than the value of head, insert the element at the front of the list.
- Otherwise, traverse the list in this way: for a particular node of the list, if the next pointer is NULL (end of list) or the value of the element (to be inserted) is less than the value of the next node, insert the element after the current node, or move to the next node.
#include <stdio.h> #include <stdlib.h> struct node{ int val; struct node *next; }; void print_list(struct node *head) { printf("H->"); while(head) { printf("%d->", head->val); head = head->next; } printf("|||\n"); } void insert_sorted(struct node **head, int value) { struct node * new_node = NULL; struct node * tmp_node = NULL; new_node = (struct node *)malloc(sizeof(struct node)); if (new_node == NULL) { printf("Failed to insert element. Out of memory"); } new_node->val = value; if(*head == NULL || value < (*head)->val) { new_node->next = *head; *head = new_node; return; } tmp_node = *head; while(tmp_node->next && value > tmp_node->next->val) { tmp_node = tmp_node->next; } new_node->next = tmp_node->next; tmp_node->next = new_node; } void main() { int count = 0, i, val; struct node * head = NULL; printf("Enter number of elements: "); scanf("%d", &count); for (i = 0; i < count; i++) { printf("Enter %dth element: ", i); scanf("%d", &val); insert_sorted(&head, val); } printf("List after insertion: "); print_list(head); }
Output:
Enter number of elements: 10 Enter 0th element: 6 Enter 1th element: 34 Enter 2th element: 5 Enter 3th element: 90 Enter 4th element: 65 Enter 5th element: 78 Enter 6th element: 65 Enter 7th element: 34 Enter 8th element: 23 Enter 9th element: 88 List after insertion: H->5->6->23->34->34->65->65->78->88->90->|||
The post Insert an Element in a Sorted Singly Linked List appeared first on QnA Plus.