Skip to content

Instantly share code, notes, and snippets.

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/50e7d411c62b31a61b3cc22b72d70a3d to your computer and use it in GitHub Desktop.
Save RafaelBroseghini/50e7d411c62b31a61b3cc22b72d70a3d to your computer and use it in GitHub Desktop.
Adding a node to a Ordered Linked List, recursively
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