先上代码在上图
参考博文参考博文
/**
* 单链表的合并
*/
public class test07 {
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l4 = new ListNode(4);
ListNode ll1 = new ListNode(1);
ListNode ll3 = new ListNode(3);
ListNode ll4 = new ListNode(4);
l1.next = l2;
l2.next = l4;
ll1.next = ll3;
ll3.next = ll4;
ListNode listNode = ListNode.mergeTwoLists(l1, ll1);
System.out.println(listNode.toString());
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
", next=" + next +
'}';
}
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//递归终止条件 : 有一个是空了
if(l1 == null || l2 == null){
return null == l1 ? l2 : l1;
}
ListNode head = null;
if(l1.val <= l2.val){ // 1 4
head = l1;
head.next = mergeTwoLists(l1.next,l2);
}else{
head = l2;
head.next = mergeTwoLists(l1,l2.next);
}
return head;
}
}
左边为深入递归
右边是一层一层返回