c ++删除节点链表导致程序崩溃

时间:2015-11-28 01:43:05

标签: c++ linked-list crash

当我运行我的删除节点功能时,它最终会崩溃命令屏幕..我知道导致崩溃的代码行。我认为它崩溃是因为我试图让指针指向一个无效的节点,但我可能错了。这是删除功能的完整代码。它似乎只在它运行时发生。这些是造成崩溃的代码行:

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


int number = 2;

//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 viewInv(InventoryList& inv, Item& heroArmor, Item& heroWeapon, Hero&     hero)
{
int x = 0;
string y;
inv.displayList();
Item equip;

cout << "Do you wish to use/equip an item? If so please enter Yes, else enter No" << endl;

cin >> y;
if (y == "Yes" || y == "yes" || y == "YES")
{
    cout << "Please enter the position corrosponding to the item you wish to use." << endl;
    cin >> x;
//calling the function to retreive the item from the inventory
    equip = inv.returnNode(x);
    cout << equip;

//calling the delete function.
    inv.deleteNode(x);
    system("pause");

    if (equip.getType() == "Blunt" || equip.getType() == "Stab" || equip.getType() == "Slash")
    {
        inv.appendNode(heroWeapon);
        heroWeapon = equip;
    }
    else if (equip.getType() == "Light" || equip.getType() == "Medium" || equip.getType() == "Heavy")
    {
        inv.appendNode(heroArmor);
        heroArmor = equip;
    }
    else if (equip.getType() == " ")
    {
        cout << "There is no item." << endl;
    }
    else
    {
        heal(hero);
    }

}

}

1 个答案:

答案 0 :(得分:0)

您正在将上一个节点设置为nodePtr,这可能会导致您尝试删除下次运行此行时已删除的内容。如果您有一个调试器或发布完整的源代码,请逐步使用调试器。