Created
November 19, 2018 22:58
-
-
Save RafaelBroseghini/50e7d411c62b31a61b3cc22b72d70a3d to your computer and use it in GitHub Desktop.
Adding a node to a Ordered 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
import sys | |
class LinkedList(object): | |
class __Node(object): | |
def __init__(self, val, next=None): | |
self.val = val | |
self.next = next | |
def setNext(self, newNext): | |
self.next = newNext | |
def __init__(self): | |
self.head = LinkedList.__Node(-sys.maxsize) | |
def add(self, val): | |
self.head = LinkedList.__add(self.head, val) | |
def __add(node, val): | |
if node == None: | |
return LinkedList.__Node(val) | |
if node.val > val: | |
newNode = LinkedList.__Node(val) | |
newNode.setNext(node) | |
return newNode | |
else: | |
node.next = LinkedList.__add(node.next, val) | |
return node | |
def __str__(self): | |
current = self.head.next | |
while current != None: | |
print(current.val, end=" -> ") | |
current = current.next | |
print(None) | |
return "" | |
if __name__ == "__main__": | |
chain = LinkedList() | |
chain.add(5) | |
chain.add(4) | |
chain.add(3) | |
chain.add(1) | |
chain.add(2) | |
print(chain) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment