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:

refer to the original poster ouyang tzu remote response:
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;
}

}
}



You don't understand application,
L1. Val & lt; L2. Val is comparing the two list the size of the value of the current node, if small l1 are the same, more mobile nodes to l1. The next compared with l2 of the current node, if small l2 links the l2 segmental l1. The next, then compare l2. The next and l1, the size of the current node.
  • Related