I'm new to link lists and have to write a few modified functions from the book to do additional things. I have to modify insert to insert by the 2nd number passed in and have it replace that position and move the number that was there up. It's inserting the number, but before the position specified. If I insert 80 and position 0, that works fine. If I insert 50 at position 20, greater then the actual length of the list, it inserts it at the end like I want. But when I try to insert 87 at position 2, it will insert the number at position 3. If I want to insert 99 in position 3, it will insert it in position 5.
Any help would be appreciated.
Thanks.
void NumberList::insertByPosition(double x, int pos)
{
ListNode *newNode; //create a new node
ListNode *nodePtr; // To traverse the list
ListNode *previousNode = 0; //the previous node
int position = 0;
//allocate a new node and store x there
newNode = new ListNode;
newNode->value = x;
//position nodePtr at the head of the list
nodePtr = head;
// Initialize previousNode to NULL.
previousNode = 0;
//skip all nodes wholse position is less then pos
while (nodePtr !=0 && position < pos)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
position++;
}
if (pos == 0)
{
head = newNode;
newNode->next = nodePtr;
}
else if (pos == position || pos > position)
{
previousNode->next = newNode;
newNode->next = nodePtr;
}
}