Hayden Gfeller
Hayden Gfeller

Reputation: 19

c++ linked list delete function leaving a hole

for my final programming project, I needed to create a linked list to hold items, and it needs to be able to delete and add items. Appending the items to linked list works fine, but when I delete and attempt to display the function, the program crashes when it reaches the spot where the deleted item once resided.

Lets say item three was the one deleted, it would output to the screen like this: Item1 (shown) Item2(shown) Then it crashes

So it seems like,atleast to me, when I use my delete function, it is leaving some kind of a 'hole' in the linked list.

The only place it does not crash when I delete from the linked list, is the head, but for some odd reason only one item is left remaining in the linked list after that.

I was wondering if someone could point where in my delete function, or my display function that is causing this error.

//sending a number to the function holding the position of the item.

void InventoryList::deleteNode(int num)
{
ListNode *previousNode; //To point to the previous node
ListNode *nodePtr; //to traverse the list


int number = 1;

//if the head is empty do nothing
if (!head)
{
    return;

}
//Determine if the first node is the value
if (1 == num)
{

    nodePtr = head->next;
    delete head;
    head = nodePtr;

}
else
{
    //intialize the node as head.
    nodePtr = head;


    //Skip nodes whose value is not equal to num.
    while (nodePtr != nullptr && number != num)
    {
        previousNode = nodePtr;
        nodePtr = nodePtr->next;

        number++;
    }
    if (nodePtr)
    {
        previousNode = nodePtr;
        previousNode->next = nodePtr->next;
        delete nodePtr;

    }
}

    }


void InventoryList::displayList()
{

int x = 1;
//used to traverse the list
ListNode *nodePtr;

//setting the list equal tot he head
nodePtr = head;

//goes through the list

    while (nodePtr)
    {
        //displaying the list.
        cout << x << nodePtr->value << endl;
        nodePtr = nodePtr->next;
        x++;

    }

 }

Upvotes: 1

Views: 122

Answers (1)

The Dark
The Dark

Reputation: 8514

In this code:

if (nodePtr)
{
    previousNode = nodePtr;
    previousNode->next = nodePtr->next;
    delete nodePtr;

}

You have an extra

    previousNode = nodePtr;

which means that you are effectively just setting nodePtr->next = nodePtr->next, which does nothing.

Just remove that line.

Upvotes: 2

Related Questions