Nov 4, 2020 at 11:44pm UTC
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 Nov 4, 2020 at 11:45pm UTC
Nov 5, 2020 at 12:31am UTC
Last edited on Nov 5, 2020 at 12:32am UTC