I am trying to mergeSort two linked lists, and have used functions
mid
- To find the midpoint of LLmerge
- To merge the sorted linked listsmergeSort
- The final function is called recursively
Following is the class structure of the Node class:
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
My code:
Node *merge(Node *head1, Node *head2)
{
Node *nh = NULL;
Node *nt = NULL;
if(head1==NULL)
{
return head2;
}
if(head2==NULL)
{
return head1;
}
if(head1->data<=head2->data)
{
nh = head1;
nt = head1;
head1 = head1->next;
}
else
{
nh = head2;
nt = head2;
head2 = head2->next;
}
while(head1!=NULL && head2!=NULL)
{
if(head1->data<=head2->data)
{
nt->next = head1;
nt = head1;
head1=head1->next;
}
else
{
nt->next = head2;
nt = head2;
head2 = head2->next;
}
}
if(head1!=NULL)
{
nt->next =head1;
}
if(head2!=NULL)
{
nt->next = head2;
}
return nh;
}
Node *mid(Node *head)
{
if(head==NULL)
{
return head;
}
Node *fast = head;
Node *slow = head;
while(fast->next!=NULL && fast->next->next!=NULL)
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
Node *mergeSort(Node *head)
{
if(head==NULL)
{
return head;
}
Node *midpoint = mid(head);
Node *half1 = head;
Node *half2 = midpoint->next;
midpoint->next = NULL;
half1 = mergeSort(half1);
half2 = mergeSort(half2);
Node *mergeHead = merge(half1,half2);
return mergeHead;
}
I am getting runtime errors. How can I get this to work?