Design an algorithm and c-program to insert a data element into sorted single linear linked list (SLLL).

 Design an algorithm and c-program to insert a data element into sorted single linear linked list (SLLL).

Algorithm: Insert sort SLLL.

Input: 1) F, address of a first node of sorted list.2) e element to be inserted.

Output: F, Updated.

Method: 

n = getnode()
[n].data = e
if ( F= = NULL )
    [n].link = = NULL 
F = n
elseif ( e < = [ F ].data ) then
[n] .link = F
f = n
else
T = F
// check the list for next node
while (( [ T ].link ! = NULL ) and ( [ [ T ] . link] . data < e ) ) do
    T = [ T ] .link
while end
[ n ].link = [ T ].link
[ T ].link = n
if ends
if ends
Algorithm ends 

// C PROGRAM

#include <stdio.h>

#include <stdlib.h>


// Structure of a node

struct Node {

    int data;

    struct Node* link;

};


struct Node* F = NULL; // Head of the list


// Function to insert a node in sorted order

void insertSorted(int data) {

    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

    if (newNode == NULL) {

        printf("Unable to allocate memory.\n");

        return;

    }


    newNode->data = data;

    newNode->link = NULL;


    // Case 1: List is empty or new node should be first

    if (F == NULL || data < F->data) {

        newNode->link = F;

        F = newNode;

    } else {

        // Find position to insert

        struct Node* current = F;

        while (current->link != NULL && current->link->data < data) {

            current = current->link;

        }


        newNode->link = current->link;

        current->link = newNode;

    }

}


// Function to create a list of n nodes in sorted order

void createList(int n) {

    int data, i;

    for (i = 1; i <= n; i++) {

        printf("Enter data for node %d: ", i);

        scanf("%d", &data);

        insertSorted(data);

    }

}


// Function to display the list

void displayList() {

    struct Node* temp = F;

    while (temp != NULL) {

        printf("%d -> ", temp->data);

        temp = temp->link;

    }

    printf("NULL\n");

}


int main() {

    int n;


    printf("Enter the total number of nodes: ");

    scanf("%d", &n);


    createList(n);


    printf("\nData in the list (sorted):\n");

    displayList();


    return 0;

}


Popular posts from this blog

Difference between sequential allocation and linked allocation

Implementing queue datastructure using c program.

Feature evaluation: Unsupervised model and supervised model