HTMLify

LeetCode - Merge Two Sorted Lists - Python
Views: 12 | Author: abh
# 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]:
        sl = ListNode(None)
        hn = sl
        while list1 and list2:
            if list1.val <= list2.val:
                sl.val = list1.val
                list1 = list1.next
            elif list2.val <= list1.val:
                sl.val = list2.val
                list2 = list2.next
            if list1 or list2:
                sl.next = ListNode(None)
                sl = sl.next
        if list1:
            ll = list1
        elif list2:
            ll = list2
        else:
            ll = None
        while ll:
            sl.val = ll.val
            ll = ll.next
            if ll:
                sl.next = ListNode(None)
                sl = sl.next
        if hn.val is None: return None
        return hn

Comments