# Hackerrank Insert a node at a specific position in a linked list solution

## Problem Statement

This challenge is part of a tutorial track by MyCodeSchool and is accompanied by a video lesson.

You’re 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. Create a new node with the given integer, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is empty.

## source code:

`````` /*
Insert Node at a given position in a linked list
The linked list will not be empty and position will always be valid
First element in the linked list is at position 0
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* InsertNth(Node *head, int data, int position)
{
// Complete this method only
// Do not write main function.
Node *cur = new Node,*temp = new Node;
temp->data = data;
temp->next = NULL;
}else{
int i=0;
while(cur!=NULL){
if(position == 0){
temp->next = cur;
}
else if(i==position-1){
temp->next = cur->next;
cur ->next = temp;
}else{
}i++;
cur= cur->next;
}
}
}
``````

** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)

1. Node InsertNth(Node head, int data, int position) {
// This is a "method-only" submission.
// You only need to complete this method.
Node temp=new Node();
temp.data=data;

temp.next=null;
}else{
int i=0;
if(position==0){
}else if(i==position-1){
}