""" links.py A linked list in python. Run this at pythontutor.com to see what's going on. $ python links.py 1 -> 2 -> 3 -> Jim M | Feb 6 | cs.bennington.college | MIT License """ class Node: """ one node in a linked list """ def __init__(self, value, next=None): self.value = value self.next = next def print_nodes(node): """ print a list starting at a given node """ while node: print(f"{node.value} -> ", end="") node = node.next print() def length_nodes_1(node): """ return the lenght of the linked list that starts at node """ # This version 1 uses an explicit loop length = 0 while node: length = length + 1 node = node.next return length def length_nodes_2(node): """ return the length of the linked list that starts at node """ # This version 2 uses recursion!!! if node: return 1 + length_nodes_2(node.next) else: return 0 def main(): # Create a linked list : 1 -> 2 -> 3 three = Node(3) two = Node(2, three) one = Node(1, two) print_nodes(one) print(f"The length of the list is {length_nodes_1(one)}.") print(f"The length of the list is (again) {length_nodes_2(one)}.") main()