I am writing a code to merge two sorted lists. The PrintList function works fine when I'm trying to display the two individual linked lists. However, when I call the MergeList function to merge the two sorted lists and try to display it through my display function, it is showing nothing on VSCode and the code terminates. I checked my code on online compilers and it said segmentation fault. How can I fix this? Here's the code:
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node (int data)
{
this->data=data;
next=NULL;
}
};
Node* takeInput()
{
int data;
cin>>data;
Node *head = NULL;
Node *tail = NULL;
while(data!=-1)
{
Node *n = new Node(data);
cin>>data;
if(head==NULL)
{
head=n;
tail=n;
}
else
{
tail->next=n;
tail=n;
}
}
return head;
}
Node* mergeList(Node *head1, Node *head2)
{
if(head1=NULL)
return head2;
if(head2=NULL)
return head1;
Node *finalHead = NULL;
if(head1->data<head2->data)
{
finalHead=head1;
head1=head1->next;
}else{
finalHead=head2;
head2=head2->next;}
Node *finalTail = finalHead;
while(head1&&head2)
{
if(head1->data<head2->data)
{
finalTail->next=head1;
head1=head1->next;
}
else{
finalTail->next=head2;
head2=head2->next;
}
finalTail=finalTail->next;
}
if(head1){
finalTail->next=head1;}
else{
finalTail->next=head2;}
return finalHead;
}
void printList(Node *head)
{
Node *temp = head;
while(temp!=NULL)
{
cout<<temp->data<<" -> ";
temp=temp->next;
}
cout<<"NULL"<<"\n";
}
int main()
{
Node *head1 = takeInput();
Node *head2 = takeInput();
printList(head1);
printList(head2);
Node *newHead = mergeList(head1,head2);
printList(newHead);
return 0;
}