merge to linked lists, but an unusual None type error is occurring

Viewed 64

Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4

  • I know this is not the optimal solution but still I'm not able to understand my mistake.*
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(ListNode):
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        lst =[]
        while(l1!=None):
            #print("I")
            lst.append(l1.val)
            l1 = l1.next
        while (l2!=None):
            #print("I")
            lst.append(l2.val)
            l2 = l2.next
        lst.sort()
        #print(lst)
        l = ListNode(0)
        #temp : ListNode()
        temp = l
       # temp.val = l.val
        for i in lst:
            temp.val = i
            temp = temp.next
        return l

error is

AttributeError: 'NoneType' object has no attribute 'val'
    temp.val = i

1 Answers

The issue is with below line

temp = temp.next

You initialize temp as l but it doesn't have any next element, it's just a single element. In other words temp.next is None so whenever you go to 2nd iteration of the for loop you will see AttributeError: 'NoneType' object has no attribute 'val'

Solution:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
lst = [1,2,3,4]

l = ListNode(lst[0])
temp = l
for i in lst[1:]:
    temp.next = ListNode(i)
    temp = temp.next
Related