Insert a node at a specific position in a linked list HackerRank Solution


Insert a node at a specific position in a linked list HackerRank Solution
Source : https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list



Source : https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list


Solution


// Karthikalapati.blogspot.com
/*
Insert Node at a given position in a linked list
First element in the linked list is at position 0
Node is defined as
class Node {
int data;
Node next;
}
*/
Node InsertNth(Node head, int data, int position) {
Node newNode = new Node();
newNode.data = data;
if (position == 0) {
newNode.next = head;
return newNode;
} else {
/* Get Node one element before desired position */
Node n = head;
for (int i = 0; i < position - 1; i++) {
n = n.next;
}
/* Insert our new Node */
newNode.next = n.next;
n.next = newNode;
return head;
}
}

4 comments:

  1. I found your this post while searching for some related information on blog search...Its a good post..keep posting and update the information. Best place to buy whiskey online

    ReplyDelete
  2. I think this is an informative post and it is very beneficial and knowledgeable. Therefore, I would like to thank you for the endeavors that you have made in writing this article. All the content is absolutely well-researched. Thanks... nigerian newspapers

    ReplyDelete
  3. A very excellent blog post. I am thankful for your blog post. I have found a lot of approaches after visiting your post. https://oncaagt.com/

    ReplyDelete