Python Merge Two Sorted Lists


  • 0
    Y
    enter code here# Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # @param {ListNode} l1
        # @param {ListNode} l2
        # @return {ListNode}
        def mergeTwoLists(self, l1, l2):
            Nlist = []
            if not l1:
                return l2
            elif not l2:
                return l1
            else:
                i = 0
                j = 0
                while i < len(l1) and j < len(l2):
                    if l1[i] < l2[j]:
                        Nlist.append(l1[i])
                        i += 1
                    else:
                        Nlist.append(l2[j])
                        j += 1
                if i == len(l1) - 1:
                    Nlist.extend(l2[j:])
                elif j == len(l2) - 1:
                    Nlist.extend(l1[i:])
            return Nlist
    

    Runtime Error Message:
    Line 20: AttributeError: ListNode instance has no attribute 'len'
    Last executed input:
    [2], [1]


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.