Skip to content

Commit 8824413

Browse files
committed
- Merge Two Sorted Lists #224
1 parent 9c5e9e5 commit 8824413

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

merge-two-sorted-lists/ayosecu.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
from typing import Optional
2+
3+
# Definition for singly-linked list.
4+
class ListNode:
5+
def __init__(self, val=0, next=None):
6+
self.val = val
7+
self.next = next
8+
9+
class Solution:
10+
"""
11+
- Time Complexity: O(n + m), n = len(list1), m = len(list2)
12+
- Space Complexity: O(1)
13+
"""
14+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
15+
# two pointers
16+
p1, p2 = list1, list2
17+
dummy = ListNode(0)
18+
current = dummy
19+
20+
while p1 and p2:
21+
if p1.val < p2.val:
22+
current.next = p1
23+
p1 = p1.next
24+
else:
25+
current.next = p2
26+
p2 = p2.next
27+
current = current.next
28+
29+
current.next = p1 if p1 else p2
30+
31+
return dummy.next
32+
33+
def printList(list):
34+
if not list:
35+
print("[]")
36+
return
37+
38+
str_list = []
39+
while list:
40+
str_list.append(str(list.val))
41+
list = list.next
42+
print("[" + ", ".join(str_list) + "]")
43+
44+
def doTest():
45+
sol = Solution()
46+
47+
list1 = ListNode(1)
48+
list1.next = ListNode(2)
49+
list1.next.next = ListNode(4)
50+
list2 = ListNode(1)
51+
list2.next = ListNode(3)
52+
list2.next.next = ListNode(4)
53+
result1 = sol.mergeTwoLists(list1, list2)
54+
printList(result1)
55+
56+
result2 = sol.mergeTwoLists(None, None)
57+
printList(result2)
58+
59+
result3 = sol.mergeTwoLists(None, ListNode(0))
60+
printList(result3)
61+
62+
doTest()

0 commit comments

Comments
 (0)