题目:
解析:
方法一:
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {//headH用来返回链表ListNode headH = new ListNode(-1);ListNode tmp = headH;//遍历两个链表while(list1 != null && list2 != null) {if(list1.val < list2.val) {tmp.next = list1;list1 = list1.next;tmp = tmp.next;}else{tmp.next = list2;list2 = list2.next;tmp = tmp.next;}}//如果一个链表遍历完就接上另一个if(list1 != null) {tmp.next = list1;}if(list2 != null) {tmp.next = list2;}return headH.next;}
方法二:递归
代码:
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {//方法二递归:if(list1 == null) return list2;else if(list2 == null) return list1;if(list1.val <= list2.val){list1.next = mergeTwoLists(list1.next,list2);return list1;} else {list2.next = mergeTwoLists(list1,list2.next);return list2;}}