Home > Back-end > Merging two order list (recursive)
Merging two order list (recursive)
Time:09-30
This is merging two ordered list of recursive code, the iteration will write, recursive write wrong, This is the official LeetCode solutions, problem: Behind the two else if why want to write the return on the inside, and l1. Next=mergeTwoLists (l1. Next, l2); Why is the l1. Next? If it is not in the l1. Val? This code is how to deal with a linked list is finished, another list hasn't finish comparing? Please advise
The class Solution { Public ListNode mergeTwoLists (ListNode ListNode l1, l2) { If (l1==null) { Return l2; } else if (l2==null) { Return l1. } else if (l1. Val & lt; L2. Val) { L1. Next=mergeTwoLists (l1. Next, l2); Return l1. } else { L2. Next=mergeTwoLists (l1 and l2. Next); Return l2; }
} }
CodePudding user response:
It is easy to understand If the l1 is less than the current node l2 current node (l1. ValOn the contrary, l2. Val CodePudding user response: