Implementing a Sorted Singly Linked List in C

A singly linked list is built using a structure containing data and a pointer to the next node. This dynamic data strcuture supports efficient insertion, deletion, and traversal operations.

Below is a concise implementation that maintains elements in ascending order during insertion:

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int value;
    struct Node* next;
} Node;

int main() {
    int count, input;
    Node* head = NULL;
    
    scanf("%d", &count);
    while (count--) {
        scanf("%d", &input);
        Node* newNode = (Node*)malloc(sizeof(Node));
        newNode->value = input;
        newNode->next = NULL;
        
        if (head == NULL || input < head->value) {
            newNode->next = head;
            head = newNode;
        } else {
            Node* current = head;
            while (current->next != NULL && current->next->value < input) {
                current = current->next;
            }
            newNode->next = current->next;
            current->next = newNode;
        }
    }
    
    for (Node* ptr = head; ptr != NULL; ptr = ptr->next) {
        if (ptr == head)
            printf("%d", ptr->value);
        else
            printf(" %d", ptr->value);
    }
    
    return 0;
}

This version simplifies insertion logic by handling three cases uniformly: inserting at the head, in the middle, or at the tail. The loop finds the correct predecesor node, after which the new node is linked in constant time.

Tags: C Linked List Data Structures Sorting algorithms

Posted on Sun, 26 Jul 2026 17:18:45 +0000 by dlgilbert