0

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

asked Feb 6, 2021 at 16:41

1 Answer 1

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.

answered Feb 6, 2021 at 16:53

1 Comment

Oh my God thanks alot that seems to be all that i was missing, my code passed all the test

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.