알고리즘

[LeetCode] 21. Merge Two Sorted Lists

유병각 2022. 4. 28. 22:38
# 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]:

        node = ListNode()
        r = node

        while (list1 or list2):
            num1, num2 = 101, 101
            if (list1):
                num1 = list1.val
            if (list2):
                num2 = list2.val


            node.next = ListNode()

            if (num1 >= num2):
                node.next.val = num2
                list2 = list2.next     
            else:
                node.next.val = num1
                list1 = list1.next  
            node = node.next

        if (r.next):
            return r.next
        else:
            return None