Skip to content

Instantly share code, notes, and snippets.

@William-Hill
Created April 28, 2018 21:11
Show Gist options
  • Save William-Hill/dab19be954a5793a76d627daf459dddf to your computer and use it in GitHub Desktop.
Save William-Hill/dab19be954a5793a76d627daf459dddf to your computer and use it in GitHub Desktop.
Insert into a sorted doubly linked list
def insert_between_nodes(current_node, new_node):
new_node.next = current_node.next
new_node.prev = current_node
current_node.next.prev = new_node
current_node.next = new_node
def SortedInsert(head, data):
new_node = Node(data)
current_node = head
while current_node:
if new_node.data > current_node.data:
if not current_node.next:
current_node.next = new_node
new_node.prev = current_node
break
elif new_node.data < current_node.next.data:
insert_between_nodes(current_node, new_node)
break
else:
current_node = current_node.next
continue
return head
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment