0%

Leetcode 21 合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

直接写就行了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:

if list1 is None and list2 is None:
return None
if list1 is None and list2 is not None:
return list2
if list1 is not None and list2 is None:
return list1

if list1.val <= list2.val:
ans = ListNode(list1.val)
list1 = list1.next
else:
ans = ListNode(list2.val)
list2 = list2.next

current = ans
while list1 and list2:
if list1.val <= list2.val:
new_node = ListNode(list1.val)
current.next = new_node
list1 = list1.next
else:
new_node = ListNode(list2.val)
current.next = new_node
list2 = list2.next

current = current.next
if list1: current.next = list1
if list2: current.next = list2
return ans