Wednesday, September 14, 2016

Code to Sort a singly link list in C

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node
{
int sData;
struct node *next;

};
struct node *start=NULL;
struct node *temp=NULL;

void insert(int lValue)
{
struct node *temp1;
temp1=malloc(sizeof(struct node *));

temp=start;
if(start == NULL )
{
start=temp1;
temp1->sData=lValue;
temp1->next=NULL;
}
else
{
while(temp->next != NULL)
{
temp=temp->next;
}
temp->next=temp1;
temp1->sData=lValue;
temp1->next=NULL;
}
}
void display()
{
struct node *temp=start;
if( NULL == start)
{
printf("Link list is empty\n");
}
else
{
while(temp->next != NULL )
{
printf(" Element is  [%d]\n",temp->sData);
temp=temp->next;
}
printf("Last Element is  [%d]\n",temp->sData);
}
}
void sort()
{
struct node *temp,*temp1;
if(NULL == start)
{
printf("Cant Sort: Link List is empty\n");
}
else
{
temp1=start;
while(temp1->next !=NULL)
{
temp=start;
while(temp->next !=NULL)
{
if(temp->sData > temp->next->sData)
{
int temp1=temp->sData;
temp->sData=temp->next->sData;
temp->next->sData=temp1;
}
temp=temp->next;
}
temp1=temp1->next;
}
}
}

int main()
{
int choice;
int lData;
while(1)
{
printf("1. Insert into Linked list\n 2. Display Link List\n 3. Sort Linked List\n 4. Exit\n Enter Your Choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter Element:\t");
scanf("%d",&lData);
insert(lData);
break;
case 2:
display();
break;
case 3:
sort();
break;
case 4:
exit(1);
break;
default:
break;
}
}
return 0;
}

No comments:

Post a Comment