Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@RafaelBroseghini
Created November 18, 2018 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RafaelBroseghini/9a8a76baebbdd1bf4c5bde5ebee169c5 to your computer and use it in GitHub Desktop.
Save RafaelBroseghini/9a8a76baebbdd1bf4c5bde5ebee169c5 to your computer and use it in GitHub Desktop.
Add a node to a Linked List, recursively
class LinkedList(object):
class __Node(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
def __init__(self, head):
self.head = LinkedList.__Node(head)
def add(self, val):
self.head = LinkedList.__add(self.head, val)
def __add(node, val):
if node.next != None:
LinkedList.__add(node.next, val)
else:
node.next = LinkedList.__Node(val)
return node
def __str__(self):
current = self.head
while current != None:
print(current.val)
current = current.next
return ""
if __name__ == "__main__":
chain = LinkedList(0)
chain.add(1)
chain.add(2)
chain.add(3)
chain.add(4)
chain.add(5)
print(chain)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment