1

I have this function:

def to_plain_list(self, current=None, result=None):
    """
    Returns a regular Python list containing the same values,
    in the same order, as the linked list using recursion without loops
    """
    if result is None:
        result = []
    if current is None:
        current = self._head
    result.append(current)
    if current.next is None:
        return result
    self.to_plain_list(current.next, result)


The only problem is the function is returning None. I've added print statements to make sure the code is being run through the function properly, and it appears it is, even doing this:

def to_plain_list(self, current=None, result=None):
    """
    Returns a regular Python list containing the same values,
    in the same order, as the linked list using recursion without loops
    """
    if result is None:
        result = []
    if current is None:
        current = self._head
    result.append(current)
    if current.next is None:
        print(result)
        return result
    self.to_plain_list(current.next, result)

And this is printed:

[<__main__.Node object at 0x0000021B35CF56D0>, <__main__.Node object at 0x0000021B35CF5710>, <__main__.Node object at 0x0000021B35CF5750>, <__main__.Node object at 0x0000021B35CF5790>, <__main__.Node object at 0x0000021B35CF57D0>]

So I know "result" contains something, but it is still returning None. Here's my code to call it:

first_list = LinkedList()
first_list.add(10)
first_list.add(20)
first_list.add(30)
first_list.add(40)
first_list.add(50)
print(first_list.to_plain_list())

Any ideas? I appreciate y'all.

Xave
  • 11
  • 1
  • 1
    There is no `return` when you recurse. The last line of the function should be `return self.to_plain_list(current.next, result)` – Matthias Feb 16 '23 at 19:10
  • See [Return, return None, and no return at all](https://stackoverflow.com/questions/15300550/return-return-none-and-no-return-at-all) for more information about why your function implicitly returns `None` – G. Anderson Feb 16 '23 at 19:12
  • Matthias, so one can't use return during recursion? – Xave Feb 16 '23 at 19:16
  • G. Anderson, I'll check that out, thank you for the link. – Xave Feb 16 '23 at 19:16
  • @Xave they are not saying you can't use return during recursion at all. Indeed, they are telling you to use it. You have to *return* the result of the recursive call. – juanpa.arrivillaga Feb 16 '23 at 19:49

0 Answers0