/*Sorting a linked list*/
#include<stdio.h>
#include<conio.h>
struct linklist
{
int data;
struct linklist *next;
};
typedef struct linklist node;
node *create_node(int val,node *address)
{
node *p;
p=(node*)malloc(sizeof(node));
p->data=val;
p->next=address;
return p;
}
node *add_at_beginning(node *head,int value)
{
return(create_node(value,head));
}
int get_length(node *head)/*Returns the number of elements in the list*/
{
int count=0;
if(head!=NULL)
{
while(head!=NULL)
{
head=head->next;
count++;
}
}
return count;
}
void print(node *head)
{
node *t_head=head;
if(head!=NULL)
{
while(t_head!=NULL)
{
printf("%d\t",t_head->data);
t_head=t_head->next;
}
printf("\n");
}
else
printf("The list is empty\n");
}
node *get_ith_node(node *head,int i)
{
if(i<=get_length(head))
{
while(i>1)
{
head=head->next;
i--;
}
return head;
}
else
return NULL;
}
node *swap(node*n1,node*n2)
{
n1->next=n2->next;
n2->next=n1;
return n2;
}
node *sort(node *head)
{
node *prev,*curr,*nxt;
int number_of_elements,count;
number_of_elements=get_length(head);
while(number_of_elements > 1)
{
count=1;
while(count < number_of_elements)
{
curr=get_ith_node(head,count);
nxt=get_ith_node(head,count+1);
if(curr->data > nxt->data)
{
if(curr == head)
head=swap(curr,nxt);
else
{
prev=get_ith_node(head,count-1);
prev->next=swap(curr,nxt);
}
}
count++;
}
number_of_elements--;
}
return head;
}
int main()
{
node *head=NULL;
head=add_at_beginning(head,3);
head=add_at_beginning(head,1);
head=add_at_beginning(head,6);
head=add_at_beginning(head,2);
head=add_at_beginning(head,5);
head=add_at_beginning(head,9);
printf("Original List:\n");
print(head);
head=sort(head);
printf("Sorted List:\n");
print(head);
getche();
}
0 comments:
Post a Comment