Sorted order insertion of linked list in c

C program for Sorted order insertion of linked list. Here problem description and explanation.

/*
    C program for
    Add node in sorted order of linked list
*/
#include <stdio.h>
#include <stdlib.h>

// Linked List LinkNode
struct LinkNode
{
    int data;
    struct LinkNode *next;
};
// Singly linked list 
struct SingleLL
{
    struct LinkNode *head;
};
// Returns the new linked list
struct SingleLL *newLinkedList()
{
    // Create memory of head and tail Nodes
    struct SingleLL *sll = (struct SingleLL *)
    malloc(sizeof(struct SingleLL));
    if (sll == NULL)
    {
        printf("Memory overflow\n");
    }
    else
    {
        sll->head = NULL;
    }
    return sll;
}
// Add new node in sorted order
void sortedAdd(struct SingleLL *sll, int data)
{
    // Create new node
    struct LinkNode *node = (struct LinkNode *)
    malloc(sizeof(struct LinkNode));
    if (node == NULL)
    {
        printf("Memory overflow to Create LinkNode\n");
        return;
    }
    else
    {
        node->data = data;
        if(sll->head == NULL || 
           sll->head->data >= data)
        {
            // When linked list empty
            // or new nodes are adding at beginning
            node->next = sll->head;
            sll->head = node;
        }
        else
        {
            struct LinkNode *temp = sll->head;

            // Find position to add new node
            while(temp->next!=NULL && 
                  temp->next->data < data)
            {
                // Visit to next node
                temp = temp->next;
            }  

            node->next = temp->next;

            // Add new node
            temp->next = node;
        }
    }

}
// Display linked list element
void display(struct LinkNode *node)
{
    if (node == NULL)
    {
        return;
    }
    struct LinkNode *temp = node;
    // iterating linked list elements
    while (temp != NULL)
    {
        printf(" %d →", temp->data);
        // Visit to next node
        temp = temp->next;
    }
    printf(" NULL\n");
}
int main(int argc, char const *argv[])
{
    struct SingleLL *sll = newLinkedList();
    // Add Linked list node
    sortedAdd(sll, 1);
    sortedAdd(sll, -3);
    sortedAdd(sll, 9);
    sortedAdd(sll, 4);
    sortedAdd(sll, 11);
    sortedAdd(sll, -7);

    printf(" Linked List \n");
    // -7 → -3 → 1 → 4 → 9 → 11 → NULL
    display(sll->head);
    return 0;
}

Output

 Linked List
 -7 → -3 → 1 → 4 → 9 → 11 → NULL


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved