-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path21.py
More file actions
38 lines (34 loc) · 1.13 KB
/
21.py
File metadata and controls
38 lines (34 loc) · 1.13 KB
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
# 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]:
# 1 or more empty linked lists
if list1 == None:
return list2
elif list2 == None:
return list1
if (list1.val <= list2.val):
newHead = list1
list1 = list1.next
else:
newHead = list2
list2 = list2.next
curNode = newHead
while (list1 != None or list2 != None):
if list1 == None:
curNode.next = list2
list2 = list2.next
elif list2 == None:
curNode.next = list1
list1 = list1.next
elif (list1.val <= list2.val):
curNode.next = list1
list1 = list1.next
else:
curNode.next = list2
list2 = list2.next
curNode = curNode.next
return newHead