Mar 3, 2014 at 8:33am UTC
I have created this program to merge two linked list into one ,but however everything is working fine but on execution it providing a segmentation fault error ( on calling merging function )
code :
#include<iostream>
#include<stdio.h>
using namespace std;
struct node{
int data;
node* link;
};
typedef node* nodeptr;
nodeptr head_first=NULL;
nodeptr head_second=NULL;
bool insert_first(int n,nodeptr &head_first)
{
nodeptr newnode = new node;
if(!newnode) return false;
newnode->data=n;
newnode->link=head_first;
head_first=newnode;
return true;
}
bool insert_second(int n,nodeptr &head_second)
{
nodeptr newnode = new node;
if(!newnode) return false;
newnode->data=n;
newnode->link=head_second;
head_second=newnode;
return true;
}
void show_first(nodeptr &head_first){
nodeptr current=new node;
current=head_first;
while(current!=NULL)
{
cout<<current->data<<" -> ";
current=current->link;
}
}
void show_second(nodeptr &head_second){
nodeptr current=new node;
current=head_second;
while(current!=NULL)
{
cout<<current->data<<" -> ";
current=current->link;
}
}
nodeptr merge_two_list(nodeptr &head_first,nodeptr &head_second)
{
nodeptr result=NULL;
if(head_first==NULL) return head_second;
else if(head_second=NULL) return head_first;
if (head_first->data <= head_second->data)
{
result = head_first;
result->link = merge_two_list(head_first->link, head_second);
}
else
{
result = head_second;
result->link = merge_two_list(head_first, head_second->link);
}
return result;
}
int main()
{
insert_first(1,head_first); //inserting into first list
insert_first(2,head_first);
insert_first(3,head_first);
insert_second(4,head_second); //inserting into second list
insert_second(5,head_second);
insert_second(6,head_second);
cout<<"List 1 :"<<endl;
show_first(head_first); //showing first list
cout<<endl;
cout<<"List 2 :"<<endl;
show_second(head_second); //showing second list
cout<<endl;
nodeptr final =new node;
final=merge_two_list(head_first,head_second); //storing result into final
while(final!=NULL) //walking from final to null
{
cout<<final->data<<" -> ";
final=final->link;
}
cout<<endl;
return 0;
}
o/p :
List 1 :
3 -> 2 -> 1 ->
List 2 :
6 -> 5 -> 4 ->
Segmentation fault (core dumped)
thanks in advance :)