Tech for good

[Neetcode/Linked List] Merge Two Sorted Linked Lists 본문

IT/Computer Science

[Neetcode/Linked List] Merge Two Sorted Linked Lists

Diana Kang 2025. 6. 2. 12:59

https://neetcode.io/problems/merge-two-sorted-linked-lists?list=neetcode150

 

NeetCode

 

neetcode.io

# 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 to simplify the merging logic
        dummy = ListNode()
        current = dummy
        
        # Iterate over both lists while both have nodes
        while list1 and list2:
            if list1.val <= list2.val:
                current.next = list1
                list1 = list1.next
            else:
                current.next = list2
                list2 = list2.next
            current = current.next
        
        # Append the rest of the remaining list
        current.next = list1 if list1 else list2
        
        # Return the merged list (starting after dummy)
        return dummy.next