c code to insert an element into the linked list in a sorted way

  • clinked-listInsertion
  • write a program to insert an element into the linked list in a sorted way

    Given a linked list that is sorted, Write a porgram to insert an element into the linked list in a sorted way.

    Code

    #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { int data; struct node *next; }; void display(struct node *r) { printf("elements of list are : "); while (r) { printf("%d ---> ", r->data); r = r->next; } printf("NULL\n"); } struct node *create(struct node *head) { int n; printf("enter the number of elments in linked list , excluding head\n"); scanf("%d", &n); struct node *t, *p; if (head == NULL) { t = (struct node *)malloc(sizeof(struct node)); printf("enter the node : "); scanf("%d", &t->data); t->next = NULL; head = t; } if (head != NULL) { do { t = (struct node *)malloc(sizeof(struct node)); printf("enter the node : "); scanf("%d", &t->data); t->next = NULL; p = head; if (head == NULL || head->data >= t->data) { t->next = head; head = t; } else { struct node *current = head; /* Locate the node before the point of insertion */ while (current->next != NULL && current->next->data < t->data) { current = current->next; } t->next = current->next; current->next = t; } n--; } while (n > 0); } return head; } int main() { struct node *head = NULL; head = create(head); display(head); return 0; }