Skip to content
Advertisement

Inserting a node at a specific position in a Linked list

I am given the pointer to the head node of a linked list, an integer to add to the list and the position at which the integer must be inserted. After inserting this node at the desired position I need to return the head node.

The code that I have written is not working for some reason and goes in an infinite loop.

JavaScript

Advertisement

Answer

JavaScript

This should be in the opposite order

JavaScript

And also the code does not check for many cases , for example as to whether the position specified is larger than the size of the linked list. Try rewriting the code , also could you mention which values are you using for testing the function. I think prev=node should throw an exception as prev was not initialized

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement