Skip to content

Commit 127714c

Browse files
committed
merge two sorted lists solution
1 parent a5bf00e commit 127714c

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
8+
if not list1:
9+
return list2
10+
if not list2:
11+
return list1
12+
13+
14+
if list1.val > list2.val:
15+
list1, list2 = list2, list1
16+
17+
head = list1
18+
19+
while list1 and list2:
20+
if not list1.next:
21+
list1.next = list2
22+
break
23+
24+
25+
if list2.val <= list1.next.val:
26+
list2_next = list2.next
27+
28+
list2.next = list1.next
29+
list1.next = list2
30+
list2 = list2_next
31+
else:
32+
list1 = list1.next
33+
34+
35+
return head

0 commit comments

Comments
 (0)