You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = [] Output: []
Example 3:
Input: list1 = [], list2 = [0] Output: [0]
Constraints:
- The number of nodes in both lists is in the range
[0, 50]
. -100 <= Node.val <= 100
- Both
list1
andlist2
are sorted in non-decreasing order.
题目大意:给定两个排好序的链表,要求把它们合并成一个仍然是排好序的链表。
解题思路:跟合并两个有序数组是一样的。用两个指针分别指向两个链表头,比较两个指针指向的当前节点值,值小的那个肯定是两个链表剩下所有节点中最小的那个,把该节点取出放入结果中,指针指向该节点的下一个节点,然后继续比较两指针指向的当前节点值,如此反复直到其中一个指针走到链表结尾,把另一个链表剩下的所有节点一次都放入结果中,这样就完成了两个有序链表的合并。
1)定义一个头节点的前节点,使得头节点被当成普通节点处理。
2)在把一个节点取出放入结果链表中时,要使其next指向空节点,以便下次指向新放入的节点。
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
preHead = ListNode(0)
p1, p2 = list1, list2
cur = preHead
while p1 and p2:
if p1.val < p2.val:
cur.next = p1
p1 = p1.next
else:
cur.next = p2
p2 = p2.next
cur.next.next = None
cur = cur.next
cur.next = p1 if p1 else p2
return preHead.next