Just have something like this where you traverse till the given position and then insert:
void addNodeAtPos(int data, int pos)
{
Node* prev = new Node();
Node* curr = new Node();
Node* newNode = new Node();
newNode->data = data;
int tempPos = 0; // Traverses through the list
curr = head; // Initialize current to head;
if(head != NULL)
{
while(curr->next != NULL && tempPos != pos)
{
prev = curr;
curr = curr->next;
tempPos++;
}
if(pos==0)
{
cout << "Adding at Head! " << endl;
// Call function to addNode from head;
}
else if(curr->next == NULL && pos == tempPos+1)
{
cout << "Adding at Tail! " << endl;
// Call function to addNode at tail;
}
else if(pos > tempPos+1)
cout << " Position is out of bounds " << endl;
//Position not valid
else
{
prev->next = newNode;
newNode->next = curr;
cout << "Node added at position: " << pos << endl;
}
}
else
{
head = newNode;
newNode->next=NULL;
cout << "Added at head as list is empty! " << endl;
}
}