자료구조와 알고리즘

21. Merge Two Sorted Lists(두 정렬 리스트의 병합)

히키맨 2023. 2. 6. 11:11

풀이 1)

# 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_node = ListNode(0)
        crnt_node = dummy_node
        
        node1 = list1
        node2 = list2
        
        while node1 and node2:
            val1 = node1.val
            val2 = node2.val
            
            if val1 <= val2:
                crnt_node.next = node1
                node1 = node1.next
                crnt_node = crnt_node.next
            else:
                crnt_node.next = node2
                node2 = node2.next
                crnt_node = crnt_node.next
        
        if node1:
            crnt_node.next = node1
        else:
            crnt_node.next = node2
        
        return dummy_node.next

풀이 2)

# 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]:
        
        if not list1 or(list2 and list1 > list2):
            list1, list2 = list2, list1
        
        if list1:
            list1.next = self.mergeTwoLists(list1.next, list2)
            
        return list1