This is a hackerrank challege question and this is the link to the question https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem, though this question might have been answered here, I was hoping on solving it on my own and came close to doing so except for some issues which I stuck with.
This is my code
def insertNodeAtPosition(head, data, position):
if position is 0:
head = SinglyLinkedListNode(data, head)
return
count = 0
while head:
if count == position - 1:
newNode = SinglyLinkedListNode(data)
newNode.next = head.next
head.next = newNode
break
head = head.next
print(head.data)
count +=1
return head
It returns the correct result minus the elements before the position - 1 element e.g instead of 16 13 1 7, it returns 13 1 7 or instead of 1 2 3 4 5 7 6, it returns 5 7 6.
I am missing something but I cant seem to point it out. Please help me
1 Answer 1
Never mess with head when you deal with linked list. Please take a variable to head and use it to iterate.
my_iter = head
Then use this my_iter in all your loops.
Also your code for insert at zero returns a head without linking it to current zero.