I am trying to write a function to add a node to a linked list at any position.
This is what I have so far:
ListNode* addNode( ListNode* pHead, ListNode* pNode, int pos )
{
if( pHead == NULL )
{
pHead = pNode;
}
else if( pos == 0 )
{
pNode->pNextNode = pHead;
pHead = pNode;
}
else
{
ListNode* pTempNode = pHead;
for(int i = 0; i < pos; i ++)
{
if(pTempNode->pNextNode != NULL)
{
pTempNode = pTempNode->pNextNode;
}
else
{
break;
}
}
pNode->pNextNode = pTempNode->pNextNode;
pTempNode->pNextNode = pNode;
pHead->pNextNode = pTempNode;
}
return pHead;
}
The problem is that when trying to add a node that isn’t in the front a few nodes are cut out in the middle. I just do not know the proper way to go about searching through the list for the position, inserting the new node, and then returning the whole list.
your code looks right except this line seems unnecessary:
also there is an off-by-one error, you’ll need to start your for loop at 1 instead of 0.