Wrew
Wrew

Reputation: 3

Modifying Linked Lists in C++

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.

Upvotes: 0

Views: 851

Answers (2)

shihongzhi
shihongzhi

Reputation: 1931

This is not necessary,you should remove this:

pHead->pNextNode = pTempNode;

It will remove the node before pTempNode.

Good Luck

Upvotes: 0

Vaughn Cato
Vaughn Cato

Reputation: 64308

your code looks right except this line seems unnecessary:

pHead->pNextNode = pTempNode;

also there is an off-by-one error, you'll need to start your for loop at 1 instead of 0.

Upvotes: 1

Related Questions