感觉思路很清晰,挨个比较
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(-1);
ListNode tmp = head;
while (l1 != null || l2 != null) {
if (l1 == null) {
tmp.next = l2;
break;
}
if (l2 == null) {
tmp.next = l1;
break;
}
if (l1.val < l2.val) {
tmp.next = l1;
tmp = l1;
l1 = l1.next;
} else {
tmp.next = l2;
tmp = l2;
l2 = l2.next;
}
}
return head.next;
}
}
用递归的思路
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
if (l1.val < l2.val) {
ListNode tmp = l1;
l1 = l1.next;
tmp.next = mergeTwoLists(l1, l2);
return tmp;
} else {
ListNode tmp = l2;
l2 = l2.next;
tmp.next = mergeTwoLists(l1, l2);
return tmp;
}
}
}