LeetCode/Grind169

21. Merge Two Sorted Lists ☆

hyunkookim 2025. 4. 22. 02:05

 

21. Merge Two Sorted Lists

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode()
        cur = dummy
        # for l1, l2 in range(min(len(list1), len(list2))): <-- ListNode 라서 이게 아님
        while list1 and list2: # 둘다 None 이 아니면
            if list1.val <= list2.val:
                cur.next = list1
                list1 = list1.next                
            else:
                cur.next = list2
                list2 = list2.next
            cur = cur.next
            
        if list1:
            cur = list1
        if list2:
            cur = list2
        return dummy.next

❌ 문제 있는 부분

if list1:
    cur = list1
if list2:
    cur = list2

이렇게 하면 cur이 그저 list1이나 list2를 가리키는 것이지, cur.next = list1 또는 cur.next = list2처럼 연결한 것이 아니에요. 결과적으로 연결 리스트가 끊겨버려서 무한 루프에 빠지게 돼요.


✅ 올바른 수정

아래처럼 cur.next = list1 또는 cur.next = list2로 연결해야 합니다:

 

최종 코드

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode()
        cur = dummy
        # for l1, l2 in range(min(len(list1), len(list2))): <-- ListNode 라서 이게 아님
        while list1 and list2: # 둘다 None 이 아니면
            if list1.val <= list2.val:
                cur.next = list1
                list1 = list1.next                
            else:
                cur.next = list2
                list2 = list2.next
            cur = cur.next
            
        cur.next = list1 if list1 else list2
        return dummy.next

 

'LeetCode > Grind169' 카테고리의 다른 글

125. Valid Palindrome  (0) 2025.04.22
121. Best Time to Buy and Sell Stock ☆  (0) 2025.04.22
20. Valid Parentheses  (0) 2025.04.22
1. Two Sum  (0) 2025.04.22
[LinkedLists: Fast and Slow Pointers] 287. Find the Duplicate Number ★★★★★  (1) 2025.04.06