Last active
March 21, 2016 02:11
-
-
Save neonbadger/1f77a9d2583487d5ec14 to your computer and use it in GitHub Desktop.
This file contains 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
""" | |
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