You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
866 B

package q21.f1;
/**
* 插队法 - 遍历迭代 o(n)
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode head = new ListNode(Integer.MIN_VALUE);
head.next = l1;
ListNode pre = head;
while (l2 != null) {
ListNode t1 = pre.next;
ListNode t2 = l2.next;
while (l2.val > t1.val) {
if (t1.next == null) {
t1.next = l2;
return head.next;
} else {
pre = pre.next;
t1 = t1.next;
}
}
pre.next = l2;
l2.next = t1;
l2 = t2;
}
return head.next;
}
}