sy1214ei 님의 블로그

[Leet Code] 21. Merge Two Sorted Lists - Python 본문

[Coding]

[Leet Code] 21. Merge Two Sorted Lists - Python

sy1214ei 2024. 11. 29. 23:33
level : Easy
Topics : Linked List | Recursion

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]:

        dummy = ListNode() # 더미 노드 생성
        current = dummy

        # list1 & list2 모두 남아있는 동안
        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
        # 남은 노드 처리
        current.next = list1 if list1 else list2
        
        return dummy.next
        
        # Time Complexity : O(n+m)
        # Space Complexity : O(1)