We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Here is a different solution in Java. Took me awhile to figure out the different test secarnios. We should keep track of the element before the given position so that we can modify the next element.
Node InsertNth(Node head, int data, int position) {
Node newNode = new Node();
Node header = head;
// scenario when head is null
if ( head == null) {
newNode.data = data;
return newNode;
}
newNode.data = data;
// scenario when we want to insert in the first element on the list
if (position == 0) {
newNode.next = head;
header = newNode;
return header;
}
// insert somewhere else 1th, 2th, 3th, etc...
// should stop the element before the position to keep track of next element and assign to a new element
for (int i=1; i < position && head.next !=null; i++) {
head = head.next;
}
if (head.next != null) {
newNode.next = head.next;
head.next = newNode;
} else {
head.next = newNode;
}
return header;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Insert a node at a specific position in a linked list
You are viewing a single comment's thread. Return to all comments →
Here is a different solution in Java. Took me awhile to figure out the different test secarnios. We should keep track of the element before the given position so that we can modify the next element.