Skip to content

Commit 97931a0

Browse files
committed
Add solution for merging two sorted lists
1 parent ff09514 commit 97931a0

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

merge-two-sorted-lists/gcount85.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
# Intuition
3+
각각의 리스트의 첫 노드를 가리키면서 병합 리스트를 생성한다.
4+
5+
# Complexity
6+
- Time complexity: list1과 list2의 길이 N, M일때 O(N+M)
7+
8+
- Space complexity: 기존 노드 연결만 바꿈 O(1)
9+
"""
10+
11+
12+
class Solution:
13+
def mergeTwoLists(
14+
self, list1: Optional[ListNode], list2: Optional[ListNode]
15+
) -> Optional[ListNode]:
16+
dummy = ListNode(0)
17+
tail = dummy
18+
19+
while list1 and list2:
20+
if list1.val <= list2.val:
21+
tail.next = list1
22+
list1 = list1.next
23+
else:
24+
tail.next = list2
25+
list2 = list2.next
26+
tail = tail.next
27+
28+
# 남은 쪽 붙이기
29+
if list1:
30+
tail.next = list1
31+
else:
32+
tail.next = list2
33+
34+
return dummy.next

0 commit comments

Comments
 (0)