/*write a c program to sort element of singly linked list in acsending
order*/
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node *next;
}*start,*q,*temp;
int n,*p;
void create();
void display();
void sort();
void main()
{
char ch='y';
int choice;
clrscr();
while(ch=='y'||ch=='Y')
{
create ();
printf("\ndo you want to continue(Y|N):-");
scanf("\n%s",&ch);
}
display();
sort();
getch();
}
void create()
{
temp=malloc(sizeof(struct node));
printf("\nenter the number:-");
scanf("%d",&temp->data);
temp->next=NULL;
n++;
if(start==NULL)
start=temp;
else
{
q=start;
while(q->next!=NULL)
{
q=q->next;
}
q->next=temp;
}
}
void display()
{
if(start==NULL)
printf("\nlinked list is empty");
else
{
printf("\nelement in singly linked list are:-\n");
q=start;
while(q!=NULL)
{
printf("%d\n",q->data);
q=q->next;
}
}
}
void sort()
{
int i,j,t;
q=start;
p=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
if(q!=NULL)
{
*(p+i)=q->data;
q=q->next;
}
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(*(p+i)>*(p+j))
{
t=*(p+i);
*(p+i)=*(p+j);
*(p+j)=t;
}
}
}
printf("\nelement after sorting\n");
for(i=0;i<n;i++)
printf("%d\n",*(p+i));
}
/*
enter the number:-
8
do you want to continue(Y|N):-y
enter the number:-1
do you want to continue(Y|N):-y
enter the number:-6
do you want to continue(Y|N):-y
enter the number:-2
do you want to continue(Y|N):-y
enter the number:-5
do you want to continue(Y|N):-n
element in singly linked list are:-
8
1
6
2
5
element after sorting
1
2
5
6
8
*/
No comments:
Post a Comment