Skip to content

Commit 75a496a

Browse files
committed
feat: Solve merge-two-sorted-lists problem
1 parent 8cb65c8 commit 75a496a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

merge-two-sorted-lists/hu6r1s.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
# 시간복잡도: O(n + m) -> 두 리스트의 모든 노드를 한 번씩 방문
8+
# 공간복잡도: O(1) -> 기존 노드 재배치, 추가 메모리 거의 없음
9+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
10+
merged_list = ListNode()
11+
tail = merged_list
12+
13+
while list1 and list2:
14+
if list1.val < list2.val:
15+
tail.next = list1
16+
list1 = list1.next
17+
else:
18+
tail.next = list2
19+
list2 = list2.next
20+
tail = tail.next
21+
22+
if list1:
23+
tail.next = list1
24+
else:
25+
tail.next = list2
26+
return merged_list.next

0 commit comments

Comments
 (0)