题目
Python
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
tail = ListNode(-1)
cur = tail
cur1 = list1
cur2 = list2
while cur1 != None and cur2 != None:
if cur1.val <= cur2.val:
cur.next, cur1 = cur1, cur1.next
else:
cur.next, cur2 = cur2, cur2.next
cur = cur.next
cur.next = cur1 if cur1 else cur2
return tail.next
Java
法1:最佳解法,使用虚拟头结点
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(-1);
ListNode tmp = dummy;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
tmp.next = list1;
list1 = list1.next;
} else {
tmp.next = list2;
list2 = list2.next;
}
tmp = tmp.next;
}
if (list1 == null) {
tmp.next = list2;
}
if (list2 == null) {
tmp.next = list1;
}
return dummy.next;
}
}
法2:代码不够简洁
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
ListNode cur = null, head = null;
while (list1 != null || list2 != null) {
if (head == null) {
if (list1.val <= list2.val) {
head = list1;
list1 = list1.next;
} else {
head = list2;
list2 = list2.next;
}
cur = head;
}
if (list1 == null) {
cur.next = list2;
break;
}
if (list2 == null) {
cur.next = list1;
break;
}
if (list1.val <= list2.val) {
cur.next = list1;
list1 = list1.next;
} else {
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
return head;
}
}