#include<iostream>
#include<stdlib.h>
using namespace std;
struct Node
{
int val;
struct Node *next;
};
typedef struct Node node;
void splithalf(node *head,node **first,node **second)
{
node *slow=head,*fast=head;
if(head==NULL || head->next==NULL)
{
*first=head;
*second= NULL;
}
else
{
slow=head;
fast=head->next;
while(fast!=NULL)
{
fast=fast->next;
if(fast!=NULL)
{
slow=slow->next;
fast=fast->next;
}
}
*first=head;
*second=slow->next;
slow->next=NULL;
}
}
node *sortedmerge(node *a,node *b)
{
node *result=NULL;
if(a==NULL)
return b;
else if(b==NULL)
return a;
if(a->val<=b->val)
{
result=a;
result->next=sortedmerge(a->next,b);
}
else
{
result=b;
result->next=sortedmerge(a,b->next);
}
return(result);
}
void mergesort(node **head_ref)
{
node *head=*head_ref;
node*a,*b;
if(head==NULL || head->next==NULL)
return;
printf("\ncount1: mergesprt\n");
splithalf(head,&a,&b);
mergesort(&a);
mergesort(&b);
printf("\ncount2: mergesort\n");
*head_ref=sortedmerge(a,b);
}
void print(node *head)
{
while(head!=NULL)
{
cout<<head->val<<endl;
head=head->next;
}
}
int main()
{
node *head;
head=(node *)malloc(sizeof(node));
head->val=10;
head->next=(node *)malloc(sizeof(node));
head->next->val=5;
head->next->next=(node *)malloc(sizeof(node));
head->next->next->val=2;
head->next->next->next=NULL;
cout<<"The present linked list are"<<endl;
print(head);
cout<<"After sorting are "<<endl;
mergesort(&head);
print(head);
}
#include<stdlib.h>
using namespace std;
struct Node
{
int val;
struct Node *next;
};
typedef struct Node node;
void splithalf(node *head,node **first,node **second)
{
node *slow=head,*fast=head;
if(head==NULL || head->next==NULL)
{
*first=head;
*second= NULL;
}
else
{
slow=head;
fast=head->next;
while(fast!=NULL)
{
fast=fast->next;
if(fast!=NULL)
{
slow=slow->next;
fast=fast->next;
}
}
*first=head;
*second=slow->next;
slow->next=NULL;
}
}
node *sortedmerge(node *a,node *b)
{
node *result=NULL;
if(a==NULL)
return b;
else if(b==NULL)
return a;
if(a->val<=b->val)
{
result=a;
result->next=sortedmerge(a->next,b);
}
else
{
result=b;
result->next=sortedmerge(a,b->next);
}
return(result);
}
void mergesort(node **head_ref)
{
node *head=*head_ref;
node*a,*b;
if(head==NULL || head->next==NULL)
return;
printf("\ncount1: mergesprt\n");
splithalf(head,&a,&b);
mergesort(&a);
mergesort(&b);
printf("\ncount2: mergesort\n");
*head_ref=sortedmerge(a,b);
}
void print(node *head)
{
while(head!=NULL)
{
cout<<head->val<<endl;
head=head->next;
}
}
int main()
{
node *head;
head=(node *)malloc(sizeof(node));
head->val=10;
head->next=(node *)malloc(sizeof(node));
head->next->val=5;
head->next->next=(node *)malloc(sizeof(node));
head->next->next->val=2;
head->next->next->next=NULL;
cout<<"The present linked list are"<<endl;
print(head);
cout<<"After sorting are "<<endl;
mergesort(&head);
print(head);
}
No comments:
Post a Comment