Algorithm for Insertion in an Ordered
Algorithm for Insertion in an Ordered
Given a sorted linked list, we need to insert a new node while maintaining the sorted order.
Algorithm:
3. If the new node should be the first node, update its next to point to the current head and
update the head.
o Traverse the list until a node is found where its next has a value greater than the new
node’s value.
C Code:
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
};
newNode->data = data;
newNode->next = NULL;
// Step 2: If the list is empty or the new node should be the first node
newNode->next = *head;
*head = newNode;
return;
current = current->next;
newNode->next = current->next;
current->next = newNode;
temp = temp->next;
printf("NULL\n");
}
// Main function
int main() {
insertInSortedOrder(&head, 30);
insertInSortedOrder(&head, 10);
insertInSortedOrder(&head, 50);
insertInSortedOrder(&head, 20);
insertInSortedOrder(&head, 40);
return 0;
Explanation
1. struct Node
2. insertInSortedOrder
3. printList
4. Main Function
o Inserts elements in sorted order.
Complexity Analysis