//Sort singly list of integers. Create unsorted and then sort.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{ int data;
struct node *next;
}node;
node *create_normal();
void print(node *head);
void sort(node *head);
int main()
{
node *head1;
printf("\nCreating Normal(unsorted) linked list \n");
head1=create_normal();
printf("\n\nLInked list(Before Sorting):\n");
print(head1);
sort(head1);
printf("\n\nLinked list(After Sorting):\n");
print(head1);
}
node *create_normal()
{ node *head=NULL,*p;
int n,x,i;
printf("\nNumber of nodes:");
scanf("%d",&n);
printf("\nEnter data:");
for(i=1;i<=n;i++)
{ scanf("%d",&x);
if(head==NULL)
{ p=head=(node*)malloc(sizeof(node));
p->next=NULL;
}
else
{p->next=(node*)malloc(sizeof(node));
p=p->next;
p->next=NULL;
}
p->data=x;
}
return(head);
}
void print(node *head)
{ printf("\n");
while(head != NULL)
{ printf("%5d",head->data);
head=head->next;
}
}
void sort(node *head)
{ int i,j,n,temp;
node *p;
/*counting number of nodes*/
for(n=0,p=head;p!=NULL;p=p->next)
n++;
for(i=1;i<n;i++)
{p=head;
for(j=0;j<n-i;j++)
{if(p->data > p->next->data)
{ temp=p->data;
p->data=p->next->data;
p->next->data=temp;
}
p=p->next;
}
}
}
No comments:
Post a Comment