Skip to content

Merge Two Lists

LeetCode Problem

# https://leetcode.com/problems/merge-two-sorted-lists/description/
# 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]:
        # base case
        if not list1:
            return list2
        if not list2:
            return list1
        # recursive case : list1 val can be smaller or greater than list2 val (lists should be sorted order)
        temp = ListNode(0)
        if list1.val < list2.val:
            temp = list1
            temp.next = self.mergeTwoLists(list1.next, list2)
        else:
            temp = list2
            temp.next = self.mergeTwoLists(list1, list2.next)
        return temp