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.
class Node { int data; Node next; } Node InsertNth(Node head, int data, int position) { int count = 0; Node node = head; Node prev = null; while(count != position){ count++; node = node.next; prev = node; } Node newNode = new Node(); newNode.data = data; newNode.next = node; if(count == 0){ head = newNode; }else{ prev.next = newNode; } return head; }
Advertisement
Answer
node = node.next; prev = node;
This should be in the opposite order
prev = node; node = node.next;
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