Search code examples
pythonrecursionlinked-listself

Return self in python class just returns NoneType


I create a linked list in python and want to build a function to find the last item, but when I design as following, the function returns "None" type. There must be something wrong with "return self" because I print "self" before return it looks fine.

class LinkNode():
    def __init__(self,value=0,next=None):
        self.val=value
        self.next=next
    
    def findlast(self):
        if self.next == None:
            return self
        else:
            self.next.findlast()

The following is to create instances

node3=LinkNode(3,None)
node2=LinkNode(2,node3)
chain=LinkNode(1,node2)
x=chain.findlast()
type(x)

NoneType


Solution

  • def findlast(self):
        if self.next == None:
            return self
        else:
            self.next.findlast()
    

    That last line is a problem since it doesn't return anything from the function, which is why you get None. You should use (also without the superfluous else, and using is with None):

    def findlast(self):
        if self.next is None:
            return self
        return self.next.findlast()
    

    However, just keep in mind this is not the ideal use case for recursion, it may be better written as:

    def findlast(obj):
        if obj is not None: # only needed if you may pass in None as self.
            while obj.next is not None:
                obj = obj.next
        return obj