Reputation: 35
So I've got this function that is supposed to take an Optional[Node] as a parameter. The Node class is recursive, and takes in data: int and next: Optional[Node] as parameters. The idea of my function is to return the last data int value associated with the linked list, and to use recursion to do so.
My function does print "Returns {head.data}" upon completion, but isn't accompanied by the return statement. It's almost as if it never reaches the return statement and just stops at the print function. I'm completely stumped.
Here's the Node class:
class Node:
"""An item in a singly-linked list."""
data: int
next: Optional[Node]
def __init__(self, data: int, next: Optional[Node]):
"""Construct a singly linked list. Use None for 2nd argument if tail."""
self.data = data
self.next = next
def __repr__(self) -> str:
"""Produce a string representation of a linked list."""
if self.next is None:
return f"{self.data} -> None"
else:
return f"{self.data} -> {self.next}"
And the problematic function:
def last(head: Optional[Node]) -> Optional[int]:
"""Returns the last value of a Linked List, or None if the list is empty."""
if head is None:
print("Returning None...")
return None
else:
if head.next is None:
print(f"Returns {head.data}")
return head.data
else:
print("Calling last...")
last(head.next)
My terminal output:
>>> last(Node(110, Node(210, Node(310, None))))
Calling last...
Calling last...
Returns 310
So, the function is supposed to return 310, but it doesn't. It just prints out the print statement and stops there. What could be wrong? Is it the line "if head is None:"? Though, it never prints out "Returning None...", so that doesn't seem to be the problem.
Upvotes: 1
Views: 229
Reputation: 27577
I believe you neglected to return last(head.next)
. Note that the else
statements aren't necessary, as the return
statements does the work for you:
def last(head: Optional[Node]) -> Optional[int]:
"""Returns the last value of a Linked List, or None if the list is empty."""
if head is None:
print("Returning None...")
return None
if head.next is None:
print(f"Returns {head.data}")
return head.data
print("Calling last...")
return last(head.next)
Upvotes: 3
Reputation: 301
You've forgotten to actually return the result of the recursive call to last
def last(head: Optional[Node]) -> Optional[int]:
"""Returns the last value of a Linked List, or None if the list is empty."""
if head is None:
print("Returning None...")
return None
else:
if head.next is None:
print(f"Returns {head.data}")
return head.data
else:
print("Calling last...")
return last(head.next) # Added return here
Upvotes: 0