Trouble with Insert and delete functions

Hey ya'll I'm having some troble with my linked list delete and insert functions. My delete function deletes the node at the given position. I'm having trouble deleting the second node in the list, and if I select the last or second to last positions, my loop condition isn't satisfied.

Delete Method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void ColorsList::deleteNode(int position)
{
    ListNode *nodePtr = head;
    
    
    if(position == 0)
    {
        head = nodePtr->next;
        cout<<"Head node deleted.\n";
        delete nodePtr;
        return;
        
    }
    else
    {
        //loop to get pointer to previous node
        for(int i = 0; i<position-1; i++)
        {
            nodePtr =nodePtr->next;
            
            ListNode *temp = nodePtr->next;
            nodePtr->next = temp->next;
            delete temp;
            cout<<"Position "<<position<<" deleted.\n";
            
            
            
        }
    }
    
    
    
    
}


My insert method deletes everything after the position it is given instead of inserting a node.

Insert Method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void ColorsList::insertNode(int position, string color)
{
    ListNode *newNode; //to represent new node
    
    ListNode *nodePtr = head;
    
    newNode = new ListNode;
    
    newNode->colorType = color;
    
    newNode->next = nullptr;
    
    
    while(nodePtr != nullptr)
    {
   
        newNode = nodePtr;
        nodePtr =nodePtr->next;
        position++;
    }
    nodePtr->next = newNode->next;
    newNode->next = nodePtr;
  
}
Last edited on
O(n) insertion & deletion operations defeat the purpose of using a singly-linked list in the first place.

Here is a fairly beginner-friendly example of insert&delete
http://www.cplusplus.com/forum/beginner/253235/#msg1113770

Here is a less-beginner friendly but somewhat more realistic example:
http://coliru.stacked-crooked.com/a/89b5f2b46975b468
Discussed in this thread
https://www.cplusplus.com/forum/beginner/270628/

Last edited on
Topic archived. No new replies allowed.