In: Computer Science
Method in C language for inserting in descending order in a single linked list. It has a head and tail variable.
#include<stdio.h>
#include<stdlib.h>
//structure for node of single linkedlist
typedef struct node
{
   int data;
   struct node* next;
}node;
//method to insert in descending order
//takes, head,tail and value as parameters
void insert_descending(node **head,node **tail,int d)
{
   struct node *n =(struct node*)malloc(sizeof(struct
node));
   n->data=d;
   n->next=NULL;
   if(*head == NULL)//if initially list is empty
   {
       *head = *tail = n;
   }
   else//if it is not empty
   {
       node *temp =
*head,*prev=NULL;
       while(temp!=NULL &&
d<temp->data)//finding position to insert
       {
           prev=temp;
          
temp=temp->next;
       }
       if(prev==NULL)
       {
          
n->next=*head;
          
*head=n;  
       }
       else if(temp==NULL)
       {
          
(*tail)->next=n;
           *tail =
n;  
       }
       else
       {
           n->next=
prev->next;
          
prev->next   =n;
       }
   }
}
//method to print linked list
void print(node *n)
{
   while(n!=NULL){
   printf("%d ",n->data);
   n=n->next;
   }
   printf("\n");
}
int main()
{
   //testing above method
   node *head=NULL,*tail = NULL;
   insert_descending(&head,&tail,2);
   insert_descending(&head,&tail,4);
   insert_descending(&head,&tail,3);
   insert_descending(&head,&tail,1);
   //printing list
   print(head);
   return 0;
}
output:
4 3 2 1
Process exited normally.
Press any key to continue . . .