I have got a small problem with this program. It takes a user's input of numbers
and sorts them by merge sort in increasing order using linked lists.
Unfortunately, a segmentation fault appears immediately after I input the numbers. Probably something to do with the merge sort function.
Help!
#include<iostream>
#include<limits>
using namespace std;
int psize,qsize,k,i;
struct node
{
int info;
node *next;
}*p,*q,*front,*front1,*rear1,*rear,*newptr,*ptr,*np,*np1;
node *create_new_node(int);
void insert (node *);
void insert1 (node *);
void display(node *);
void MergeSort(node *,int);
void copy(node *,node *);
int main()
{
int length=0;
front=rear=NULL;
int inf;
char ch='y';
inf=INT_MIN;
newptr=create_new_node(inf); //assigning least integer value to first node
if(newptr==NULL)
{
cout<<"\nCannot create new node..";
return 0;
}
insert(newptr); //calling fuction to insert new node to the linked list
while(ch=='y'||ch=='Y')
{
cout<<"\nEnter information for the new node..";
cin>>inf;
newptr=create_new_node(inf);
if(newptr==NULL) //checking if new node creation is successful
{
cout<<"\nCannot create new node..";
return 0;
}
insert(newptr);
length++;
cout<<"\nNow the list is:\n";
display(front);
cout<<"\nPress Y to enter more nodes, N to exit..";
cin>>ch;
}
MergeSort(front,length);
}
void MergeSort(node *np,int len)
{
p = np ;
q = np ;
int k = 1;
for ( i=0;i<k;i++)
{
q = q->next;
}
qsize = 0;
psize=0 ;
int counter = 0 ;
while(k<=len/2)
{
while (counter<len)
{
while((psize<k)&&(qsize<k))
{
if((q==NULL)&&(p==NULL))
break;
if((q->info)<(p->info))
{
newptr = create_new_node(q->info);
insert1(newptr);
q = q->next;
qsize++;
counter++;
}
else
{
newptr = create_new_node(p->info);
insert1(newptr);
p = p->next;
psize++;
counter++;
}
}
p = q;
for ( i=0;i<k;i++)
{
q = q->next;
}
}
k=2*k;
copy(front1,front);
counter = 0;
qsize = 0;
psize=0 ;
}
display(front1);
}
node *create_new_node(int n) //fuction to create new node
{
ptr=new node;
ptr->info=n;
ptr->next=NULL;
return ptr;
}
void copy(node *np,node *np1)
{
while(np!=NULL)
{
np1 = np;
np=np->next;
}
}
void insert(node *np) //function to insert new node to linked list
{
if((front==NULL)&&(rear==NULL))
{
front=np;
rear=np;
}
else
{
rear->next=np;
rear = np;
}
}
void insert1(node *np)
{
if((front1==NULL)&&(rear1==NULL))
{
front1=np;
rear1=np;
}
else
{
rear1->next=np;
}
}
void display(node *np) //function to display the list
{
while(np!=NULL)
{
cout<<np->info<<"->";
np=np->next;
}
cout<<"!!!";
}