LeetCode 合并两个有序链表(递归实现)
乍看上去,这段代码不是很容易理解,但是代码很经典。
记住一句话,递归是基于功能的,对于后面已经排好序的链表,只需要排好前面的节点就好了。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
//需要返回的头指针
ListNode head = null;
if (l1.val <= l2.val){
//对于对象,这地方是引用传值。
head = l1;
head.next = mergeTwoLists(l1.next, l2);
} else {
head = l2;
head.next = mergeTwoLists(l1, l2.next);
}
return head;
}
}
算法,有看不懂的地方,画个图,举个例子就能理解了。