Merge 2 sorted LL

on Tuesday, November 24, 2009


Two sorted singly Linked List are given. Write a code to merge them. Your code should be inplace.














SOLUTION

node *merge(node *h1, node *h2){
if ( !h1 && !h2) return NULL;
if( !h1) return h2;
if (!h2) return h1;
if ( h1->data < h2->data ){
h1 ->next = merge(h1->next, h2);
return h1;
}
else {
h2->next = merge(h1,h2->next);
return h2;
}
}

4 comments:

anshul410 said...

what do you mean by " code should be inplace " .
Please explain...

anshul410 said...

the link for the code is :-

http://fwcomp.pastebin.com/f255b4623

hifun said...

anshul410:
2 points:
1.Inplace means u cant use extra space by urslef. U can use system stack though.
2.Run time faults in your code:
(a) for inserting 1 node, u r allocating memory 3 times.
(b) due to (a) ur display function is going into an infinite loop.

hifun said...

anshul410:
Mergin code is correct though.

Post a Comment