Created
November 18, 2018 16:34
-
-
Save RafaelBroseghini/9a8a76baebbdd1bf4c5bde5ebee169c5 to your computer and use it in GitHub Desktop.
Add a node to a Linked List, recursively
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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