Skip to content

Commit aa7f995

Browse files
committed
feat: [Week 04-1] solve merge-two-sorted-lists
1 parent 1d9e0e1 commit aa7f995

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

merge-two-sorted-lists/Chaedie.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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(
8+
self, list1: Optional[ListNode], list2: Optional[ListNode]
9+
) -> Optional[ListNode]:
10+
"""
11+
Solution:
12+
1) 리스트1 리스트2가 null 이 아닌 동안 list1, list2를 차례대로 줄세운다.
13+
2) list1이 남으면 node.next = list1로 남은 리스트를 연결한다.
14+
3) list2가 남으면 list2 를 연결한다.
15+
16+
Time: O(n)
17+
Space: O(1)
18+
"""
19+
dummy = ListNode()
20+
node = dummy
21+
22+
while list1 and list2:
23+
if list1.val < list2.val:
24+
node.next = list1
25+
list1 = list1.next
26+
else:
27+
node.next = list2
28+
list2 = list2.next
29+
node = node.next
30+
31+
if list1:
32+
node.next = list1
33+
elif list2:
34+
node.next = list2
35+
36+
return dummy.next

0 commit comments

Comments
 (0)