将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
法一:
1 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 2 ListNode dumy = new ListNode(0); 3 pjin(dumy,l1,l2); 4 return dumy.next; 5 } 6 7 public void pjin(ListNode cur,ListNode l1,ListNode l2){ 8 if(l1 == null){ 9 cur.next = l2; 10 return; 11 }else if(l2 == null){ 12 cur.next = l1; 13 return; 14 } 15 16 if(l1.val <= l2.val){ 17 cur.next = l1; 18 pjin(l1,l1.next,l2); 19 }else { 20 cur.next = l2; 21 pjin(l2,l1,l2.next); 22 } 23 24 }
递归
法二:
1 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 2 ListNode dumy = new ListNode(0); 3 ListNode cur = dumy; 4 while (l1 != null && l2 != null){ 5 if(l1.val <= l2.val){ 6 cur.next = l1; 7 l1 = l1.next; 8 }else { 9 cur.next = l2; 10 l2 = l2.next; 11 } 12 cur = cur.next; 13 } 14 if(l1 == null){ 15 cur.next = l2; 16 }else { 17 cur.next = l1; 18 } 19 return dumy.next; 20 }
迭代
原文:https://www.cnblogs.com/boboboo610/p/13232328.html