m1ndy5's coding blog

LeetCode 21. Merge Two Sorted Lists with Python 본문

알고리즘 with python/알고리즘 스터디

LeetCode 21. Merge Two Sorted Lists with Python

정민됴 2024. 1. 6. 17:33

https://leetcode.com/problems/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]:

        # 새로운 리스트노드 생성
        curr = dummy = ListNode()
        while list1 and list2:
            # 더 작은 값을 현재 뒤에다 붙임
            if list1.val < list2.val:
                curr.next = list1
                list1 = list1.next
            else:
                curr.next = list2
                list2 = list2.next
            curr = curr.next

        # 남아있는 리스트를 그 뒤에 붙임
        if list1 or list2:
            curr.next = list1 if list1 else list2

        # 처음에 의미없는 헤드 뒤부터
        return dummy.next

list1과 list2를 비교하면서 새로운 연결리스트에 값을 붙이는 방법이다.
이 때 둘중에 하나가 None이 되면 남아있는 리스트를 고대로 뒤에 붙이면 된다.
dummy의 헤드는 의미없는 노드이므로 뒤를 출력한다.

책 코드

def mergeTwoLists(self, l1: ListNode, l2: ListNode):
    # l1 기준으로 정렬
    # l1이 비었거나 l1이 더 값이 크면 l2를 l1으로 바꿈
    if (not l1) or (l2 and l1.val > l2.val):
        l1, l2 = l2, l1

    # l1이 None일때까지 계속 재귀
    if l1:
        l1.next = self.mergeTwoLists(l1.next, l2)

    return l1

굉장히 간단하게 재귀로 풀었다.
따로 새로운 연결리스트를 만들지 않고 l1에 계속 붙이는게 신기했던 코드였다.