Algorithm for Insertion in an Ordered (Sorted) Singly Linked List
Given a sorted linked list, we need to insert a new node while maintaining the sorted order.
Algorithm:
1. Create a new node with the given data.
2. If the list is empty, set the new node as the head.
3. If the new node should be the first node, update its next to point to the current head and
update the head.
4. Otherwise, find the correct position:
o Traverse the list until a node is found where its next has a value greater than the new
node’s value.
o Insert the new node between these two nodes.
5. Update pointers to maintain the list’s integrity.
C Code:
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
struct Node* next;
};
// Function to insert in a sorted linked list
void insertInSortedOrder(struct Node** head, int data) {
// Step 1: Create a new node
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
// Step 2: If the list is empty or the new node should be the first node
if (*head == NULL || (*head)->data >= data) {
newNode->next = *head;
*head = newNode;
return;
// Step 3: Traverse to find the correct position
struct Node* current = *head;
while (current->next != NULL && current->next->data < data) {
current = current->next;
// Step 4: Insert the new node in its correct position
newNode->next = current->next;
current->next = newNode;
// Function to print the linked list
void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
printf("NULL\n");
}
// Main function
int main() {
struct Node* head = NULL; // Initialize an empty list
// Insert elements while maintaining order
insertInSortedOrder(&head, 30);
insertInSortedOrder(&head, 10);
insertInSortedOrder(&head, 50);
insertInSortedOrder(&head, 20);
insertInSortedOrder(&head, 40);
// Print the linked list
printList(head); // Output: 10 -> 20 -> 30 -> 40 -> 50 -> NULL
return 0;
Explanation
1. struct Node
o Defines a node with data and a next pointer.
2. insertInSortedOrder
o Creates a new node with given data.
o Checks if it should be the first node.
o Traverses the list to find the correct position.
o Inserts the node and updates the pointers.
3. printList
o Prints the linked list.
4. Main Function
o Inserts elements in sorted order.
o Prints the final sorted linked list.
Complexity Analysis
• Insertion (Best & Average Case): O(n)
• Insertion (Worst Case - At the End): O(n)
• Insertion (At the Beginning): O(1)