-1

Guys I was tried to merge two sorted Single Linked List in sorted order. In SO, I found a recursive approach to do that. I was tried hard to understand the code, but wasn't able to fully understand! Are anyone there, who can help me to figure it out clearly. Thanks in advance!

Here is the code snippets:

Node MergeLists(Node list1, Node list2) {
 if (list1 == null) return list2;
 if (list2 == null) return list1;

 if (list1.data < list2.data) {
   list1.next = MergeLists(list1.next, list2);
   return list1;
 } else {
   list2.next = MergeLists(list2.next, list1);
   return list2;
 } 
}

Link: Interview: Merging two Sorted Singly Linked List

SORRY, for wasting your time! :(

Papai from BEKOAIL
  • 1,469
  • 1
  • 11
  • 17
  • That algorithm requires stack space directly proportional to the number of items in both lists. If your lists are even moderately large, that's going to blow the stack. – Jim Mischel Mar 01 '19 at 14:19

2 Answers2

1

This is what I can add to the code:

Node MergeLists(Node list1, Node list2) {
 if (list1 == null) return list2;      //Exit strategy
 if (list2 == null) return list1;      //Exit strategy

 if (list1.data < list2.data) {      //If current item in list1 is less than current 
                                     //item in list2 we put the item of list1 in our
                                     //sorted list and continue the algorithm recursivly
                                     //and add the node from recursive function to list1.next
   list1.next = MergeLists(list1.next, list2);
   return list1;
 } else {                            //exactly like above but this time we continue with list2
   list2.next = MergeLists(list2.next, list1);
   return list2;
 } 
}
Lrrr
  • 4,755
  • 5
  • 41
  • 63
1
1. Node MergeLists(Node list1, Node list2) {
2.   if (list1 == null) return list2;
3.   if (list2 == null) return list1;

4.   if (list1.data < list2.data) {
5.     list1.next = MergeLists(list1.next, list2);
6.     return list1;
7.   } else {
8.     list2.next = MergeLists(list2.next, list1);
9.     return list2;
10.  } 
11. }

Initially each of the two linked lists (LL1 and LL2), will be sorted (individually). The code only merges them. Illustrating with a SIMPLE example

eg. LL1; 1->3->4

LL2: 6->8->9

since list1.data < list2.data (line 4) will always be true (till the base exit condition (line 2)), LL1 will be recursed till the end. And finally, the next of the last element (of LL1) will point to the first element of LL2 (line 5). This way the 2 LLs will be merged and we will get 1->3->4->6->8->9

Of course, with a more complex example there will be more recursions.

Syed Waris
  • 1,056
  • 1
  • 11
  • 16