原题是LeetCode21,提供两个有序链表,合并到一起,有递归和非递归的解法,以简单高效为本。递归重点的是要考虑边界条件,空值判断,以及对应值比较后,以哪个作为后继的节点,如L1,L2,当L1 <= L2 的值,则取当前L1作为节点,同时L1的后继和L2再去按条件合并;反之L2 <= L1 同理。以下代码:
/**
* Created by igoso on 18-1-24.
* 1->2->4
* 1->3->4
*/
public class Leet21 {
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
l1.next = new ListNode(2);
l1.next.next = new ListNode(4);
ListNode l2 = new ListNode(1);
l2.next = new ListNode(3);
l2.next.next = new ListNode(4);
ListNode l3 = mergeListNode(l1, l2);
System.out.println(l3);
}
public static ListNode mergeListNode(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val <= l2.val) {
//重点在这里,选择当前节点,后继继续合并
l1.next = mergeListNode(l1.next, l2);
return l1;
} else {
l2.next = mergeListNode(l1, l2.next);
return l2;
}
}
}
class ListNode {
ListNode next;
int val;
public ListNode(int val) {
this.val = val;
}
}