Issue with Reverse Link List – Leetcode Problem NoneType Error

Question:

I am attempting to reverse a link list as per this leetcode problem: ReverseLL

My code:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur = head
        nxt = cur.next
        while nxt != None:
            temp = nxt.next
            nxt.next = cur
            cur = nxt
            nxt = temp
        
        head.next = None
        head = cur
        return head

However, I am getting an attribute error in the line:

    nxt = cur.next

Error message: AttributeError: 'NoneType' object has no attribute 'next'

But I’m not too sure why cur is a noneType when I have assigned it to be head?

Asked By: Olivia

||

Answers:

Because head also can be None, before assignment do

if head is None:
    return head
Answered By: Polatkan Polat

The problem here is, you are trying to access the next attribute of cur immediately after initializing it to head, without first checking if head is None. So any input to reverseList if empty, will result in Attribute error in your case.

You can check for the case where head is None before the while loop.

if head is None:
  return None
Answered By: Kiran Kandel