Hey everyone, can someone explain to me why the array problem works but the count problem doesn't?
Write a function, linked_list_values, that takes in the head of a linked list as an argument. The function should return a list containing all values of the nodes in the linked list.
def linked_list_values(head):
result = []
recursive_approach(head, result)
return result
def recursive_approach(head, result):
if head is None:
return
result.append(head.val)
recursive_approach(head.next, result)
a = Node("a")
b = Node("b")
c = Node("c")
d = Node("d")
a.next = b
b.next = c
c.next = d
# a -> b -> c -> d
linked_list_values(a) # -> [ 'a', 'b', 'c', 'd' ]
Write a function, sum_list, that takes in the head of a linked list containing numbers as an argument. The function should return the total sum of all values in the linked list.
def sum_list(head):
count = 0
add_nums(head, count)
return count
def add_nums(head, count):
if head is None:
return
count += head.val
add_nums(head.next, count)
a = Node(2)
b = Node(8)
c = Node(3)
d = Node(-1)
e = Node(7)
a.next = b
b.next = c
c.next = d
d.next = e
# 2 -> 8 -> 3 -> -1 -> 7
sum_list(a) # 19
Actual answer = 0
Definition of Node
:
class Node:
def __init__(self, val):
self.val = val
self.next = None