merge sort problem
i had 2 linked lists and i want to merge them the out put is different . please help me . thanks .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#include<iostream>
using namespace std;
struct node {
int data;
node *next;
};
void add(node **head,int x)
{
node *ptr=new node;
ptr->data=x+1;
if(*head==NULL)
{
*head=ptr;
ptr->next=NULL;}
else
{
ptr->next=*head;
*head=ptr;
}
}
void print( node* head)
{
if(head == NULL)
return;
print(head->next);
cout<< head->data<<" ";
}
void merge(node **head3,node **head1,node **head2)
{
node *loc,*ptr=*head1;
for(loc=*head1;loc->next!=NULL;loc=loc->next)
ptr=ptr->next;
ptr->next=*head2;
*head3=*head1;
node *cur=*head3,*cur2=*head3;
int min=cur->data;
for(cur=cur->next;cur!=NULL;cur=cur->next)
{if(cur->data<min)
min=cur->data;
cur2->data=min;
cur2=cur2->next;}
}
int main()
{
node *head1=NULL,*head2=NULL,*head3=NULL;
for(int i=0;i<5;i++)
add(&head1,i);
for(int i=0;i<5;i++)
add(&head2,i+5);
cout<<endl;
merge(&head3,&head1,&head2);
cout<<endl;
print(head3);
system("pause");
return 0;
}
|
Are you trying removing the nodes from each list and putting them into the new node or are you copying your link list into a new node?
yes it's right
Topic archived. No new replies allowed.