Tuesday, May 19, 2009

Link List Sorting

#include
#include

struct node
{
int data;
struct node *next;
}*head, *p, *q;

struct node *create();
void display(struct node *head);
void sort(struct node *head);
struct node *merge(struct node *p, struct node *q);

void main()
{
int ch;
struct node *head1, *head2, *r, *head3;
clrscr();
do
{
printf("\n\nWhat operation u have to do?");
printf("\n1.Create\n2.Sort\n3.Merge\n4.Exit\nEnter:");
scanf("%d", &ch);
switch(ch)
{
case 1:
p = create();
printf("\nList is:");
display(head);
break;

case 2:
create();
sort(head);
printf("\nSorted list is:");
display(head);
break;

case 3:
printf("\n\nEnter 1st list:");
head1 = create();
printf("\n1st List is:");
display(head1);
sort(head1);
printf("\n1st Sorted list is:");
display(head1);
printf("\n\nEnter 2nd list:");
head2 = create();
printf("\n\n2nd List is:");
display(head2);
sort(head2);
printf("\n2nd Sorted list is:");
display(head2);
head3 = merge(head1,head2);
printf("\nMerged list is:");
display(head3);

case 4:
exit();
break;
}
}while(ch!=4);
getch();
}

struct node *create()
{
int x;
char ins;
head = NULL;
p = (struct node*) malloc(sizeof(struct node));
printf("\nEnter 1st data:");
scanf("%d",&x);
p->next = NULL;
p->data = x;
head = p;
printf("\nDo u wanna insert more data?(y:yes/n:no)");
scanf("%s",&ins);
p = head;
while(ins =='y')
{
q = (struct node*) malloc(sizeof(struct node));
printf("\nEnter data:");
scanf("%d",&x);
q->data = x;
p->next = q;
p = q;
q->next = NULL;
printf("\nDo u wanna insert more data?(y:yes/n:no)");
scanf("%s",&ins);
}
return(head);
}

void display(struct node *head)
{
if(head == NULL)
printf("\nSorry!!!!\nNo data available in list!!!!");
p = head;
while(p!=NULL)
{
printf(" %d",p->data);
p = p->next;
}
}

void sort(struct node *head)
{
int temp;
if(head == NULL)
printf("\nSorry no data available!!!!!");
q = (struct node*) malloc(sizeof(struct node));
p = head;

for(p=head; p!=NULL; p=p->next)
{
for(q=p->next; q!=NULL; q=q->next)
{
if(p->data > q->data)
{
temp = p->data;
p->data = q->data;
q->data = temp;
}
}
}
}

struct node *merge(struct node *p, struct node *q)
{
struct node *head4, *head3, *r;
head4 = r;

while(p!=NULL && q!=NULL)
{
if(p->data == q->data)
{
r->data = p->data;
r = r->next;
p = p->next;
q = q->next;
}
else if(p->data <>data)
{
r->data = p->data;
r = r->next;
p = p->next;
}
else if(p->data > q->data)
{
r->data = q->data;
r = r->next;
q = q->next;
}
}
while(p!=NULL)
{
r->data = p->data;
r = r->next;
p = p->next;
}
while(q!=NULL)
{
r->data = q->data;
r = r->next;
q = q->next;
}

return(head4);
}

No comments:

Post a Comment