Skip to content

Instantly share code, notes, and snippets.

@neonbadger
Last active March 21, 2016 02:11
Show Gist options
  • Save neonbadger/1f77a9d2583487d5ec14 to your computer and use it in GitHub Desktop.
Save neonbadger/1f77a9d2583487d5ec14 to your computer and use it in GitHub Desktop.
"""
Hackerrank solution.
Insert a node at a specific position in a linked list.
"""
def InsertNth(head, data, position):
new_node = Node(data)
count = 0
if head is None:
head = new_node
return head
elif position == 0:
new_node.next = head
head = new_node
return head
else:
# 0 -> 1
# 0 -> new -> 1
# prev cur
curr = head
prev = None
while position > 0:
prev = curr
curr = curr.next
position -= 1
prev.next = new_node
new_node.next = curr
return head
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment