将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4.
1 public class MergeTwoSortedLists { 2 private class ListNode { 3 int val; 4 ListNode next; 5 6 ListNode(int x) { 7 val = x; 8 } 9 } 10 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 11 if(l1 == null) { 12 return l2; 13 } 14 if(l2 == null) { 15 return l1; 16 } 17 ListNode result = new ListNode(0); 18 ListNode curRes = result; 19 ListNode curNode1 = l1; 20 ListNode curNode2 = l2; 21 while(curNode1 != null && curNode2 != null) { 22 if(curNode1.val < curNode2.val) { 23 curRes.next = new ListNode(curNode1.val); 24 curNode1 = curNode1.next; 25 curRes = curRes.next; 26 }else { 27 curRes = new ListNode(curNode2.val); 28 curNode2 = curNode2.next; 29 curRes = curRes.next; 30 } 31 } 32 /* while(curNode1 != null) { 33 curRes.next = new ListNode(curNode1.val); 34 curRes = curRes.next; 35 curNode1 = curNode1.next; 36 } 37 38 while(curNode2 != null) { 39 curRes.next = new ListNode(curNode2.val); 40 curRes = curRes.next; 41 curNode2 = curNode2.next; 42 }*/ 43 //无需循环判断,其中一个为空,则将不为空的直接赋值即可 44 if(curNode1 != null) { 45 curRes.next = curNode1; 46 }else { 47 curRes.next = curNode2; 48 } 49 return result.next; 50 } 51 }