-
Notifications
You must be signed in to change notification settings - Fork 0
/
21.py
42 lines (40 loc) · 1.28 KB
/
21.py
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
38
39
40
41
42
# 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 not (list1 or list2):
# return None
# tmp = list()
# while list1 and list2:
# if not list1 or list1.val > list2.val:
# tmp.append(list2.val)
# list2 = list2.next
# else:
# tmp.append(list1.val)
# list1 = list1.next
# while list1:
# tmp.append(list1.val)
# list1 = list1.next
# while list2:
# tmp.append(list2.val)
# list2 = list2.next
#
# ans = ListNode(val=tmp[-1])
# for i in reversed(tmp[:-1]):
# ans = ListNode(val=i, next=ans)
# return ans
dummy = ListNode()
tmp = dummy
while list1 and list2:
if list1.val <= list2.val:
tmp.next = list1
list1 = list1.next
else:
tmp.next = list2
list2 = list2.next
tmp = tmp.next
tmp.next = list1 or list2
return dummy.next