Program to create a Sorted Linked List

Singly Linked List – Creation Sorted

Program to create a Sorted Linked List

Creating a Sorted Linked List involves insertion of a new node in the linked list such that the order of the list is preserved.  The order to be retained in the list may be chosen as either ascending or descending order.

/*Program for linked list creation,insertion and deletion.*/
/*Creation of Sorted Linked List*/

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

struct list
{int n;
struct list *next;
}*head=NULL;

struct list *createnode()
{struct list *temp;
temp=(struct list*)malloc(sizeof(struct list));
return temp;
}

struct list *makenode(int x)
{struct list *temp;
temp=createnode();
temp->n=x;
temp->next=NULL;
return temp;
}

/*Insertion condition-At the end*/
/*New element is inserted at the end*/

void insertend(int x)
{
struct list *temp1,*temp2,*ptr=makenode(x);
if(head==NULL)
{head=ptr;
}
else
{
if(head->n>x)
{ptr->next=head;
head=ptr;
}
else
{
temp1=head;
while((temp1->n<x) && (temp1!=NULL))
{temp2=temp1;
temp1=temp1->next;
}
ptr->next=temp2->next;
temp2->next=ptr;
}
}
}
/* else
{if(head->next==NULL)
{
if(head->n<x)
head->next=ptr;
else
{ptr->next=head;
head=ptr;
}
}
else
{
temp=head;
while((temp->next->n<x) && (temp->next!=NULL))
temp=temp->next;

if(temp->next==NULL)
temp->next=ptr;
else
{ptr->next=temp->next;
temp->next=ptr;
}
}
}

}

Deletion condition-At the beginning*/

void delnode()
{struct list *temp;
if(head==NULL)
{printf(“List is empty!”);
return;
}
temp=head;
head=head->next;
free(temp);
}

/*Displaying list*/

void displaylist()
{
struct list *temp;
if(head==NULL)
{printf(“nList is empty.”);
return;
}
temp=head;
while(temp!=NULL)
{printf(“%d->”,temp->n);
temp=temp->next;
}
printf(“bb “);
}

void main()
{
int ch,num;
while(1)
{
clrscr();
printf(“nCreation of Sorted Linked List-Menu”);
printf(“nn1. Insert”);
printf(“n2. Delete”);
printf(“n3. Display”);
printf(“n4. Exit”);
printf(“nnEnter your choice?”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: printf(“nEnter any number?”);
scanf(“%d”,&num);
insertend(num);
break;
case 2:
delnode();
break;
case 3:
displaylist();
break;
case 4:
exit(0);
default:
printf(“Invalid choice!”);
}
getch();
}
}