code_dominar
code_dominar

Reputation: 45

Getting error "AttributeError: 'NoneType' object has no attribute 'next'"

I'm trying to merge two sorted linked lists. What am I doing wrong? I am getting below error when trying to run for the mentioned input:

File "main.py", line 90, in <module>
    newHead = mergeTwoSortedLinkedLists(head1, head2)
  File "main.py", line 30, in mergeTwoSortedLinkedLists
    dummy.next=head2
AttributeError: 'NoneType' object has no attribute 'next'

Input:

LL1: 10 10 22 -1
LL2: 3 8 8 36 -1

Expected Output:

3 8 8 10 10 22 36
def mergeTwoSortedLinkedLists(head1, head2):
    
        # Write your code here
        if head1 is None and head2 is None:
            return None
        if head1 is None:
            return head2
        if head2 is None:
            return head1
        
        dummy=curr=None
      
        while head1 and head2:
            if head1.data<head2.data:
                #print("head1: ",head1.data)
                dummy.next=head1
                head1=head1.next
               
            else:
                #print("head2 :",head2.data)      
                dummy.next=head2
                head2=head2.next
            dummy=dummy.next
        if head1 is None:
            dummy.next=head2
        else:
            dummy.next=head1         
        
        
        return curr.next  

Upvotes: 0

Views: 2363

Answers (1)

Josh D
Josh D

Reputation: 23

NoneType is used as a sort of default value in Python, like null. It's technically the return value for a method that doesn't have a return value. https://appdividend.com/2021/02/17/what-is-nonetype-object-in-python/#:~:text=In%20Python%2C%20there%20is%20no,not%20passed%20to%20the%20function.

Your issue is at line 30: dummy=curr=None assigns dummy to be this NoneType, which doesn't really have any value. Immediately after this, you try to use dummy.next=head1 in your conditionals, which fails because NoneType isn't able to have this attribute. Try initializing dummy to a non-NoneType value, like head1, or a new instance of the class/object used to create your head1 / head2 variables.

Upvotes: 1

Related Questions