Skip to content

Instantly share code, notes, and snippets.

@f0lie
Created December 13, 2020 05:46
Show Gist options
  • Save f0lie/8931e41a1972007c2fb85e07ad538461 to your computer and use it in GitHub Desktop.
Save f0lie/8931e41a1972007c2fb85e07ad538461 to your computer and use it in GitHub Desktop.
Python Recursive __repr__ for Linked Lists
class Node:
def __init__(self, val=0, next=None):
self.next = next
self.val = val
def __repr__(self):
# Note that __repr__ is meant to be able "copy and paste" into the console and create itself
return f"Node({self.val}, {self.next})"
if __name__ == "__main__":
head = Node(0)
node = head
for i in range(1,3):
node.next = Node(i)
node = node.next
print(head)
# This showcases how you built another linked list from using the recursive __repr__
node.next = eval(str(head))
print(head)
"""
Node(0, Node(1, Node(2, None)))
Node(0, Node(1, Node(2, Node(0, Node(1, Node(2, None))))))
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment