删除链接列表中的元素时出现随机整数

时间:2015-08-03 07:36:13

标签: c++ random linked-list integer

当我尝试从链表中删除某个元素时,某些元素最终会以某种方式获取随机值来代替其原始元素。有什么问题?

void removeSpaceShipPower(SpaceShip *x, int y)
{
    SpaceShip *current = x;
    SpaceShip *toDelete = NULL;
    SpaceShip *next = NULL;
    while(current != NULL)
    {
        if(current->nextShip->power == y)
        {
            next = current->nextShip->nextShip;
            current->nextShip = next;
            toDelete = current->nextShip;
            free(toDelete);
            return;
        }
        current = current->nextShip;
    }
}

主:

int main()
{
    SpaceShip *freeList = new SpaceShip;
    freeList->power = 50;
    freeList->health = 100;
    SpaceShip *freeList2 = new SpaceShip;
    freeList2->power = 25;
    freeList2->health = 100;
    SpaceShip *freeList3 = new SpaceShip;
    freeList3->power = 75;
    freeList3->health = 100;
    SpaceShip *freeList4 = new SpaceShip;
    freeList4->power = 100;
    freeList4->health = 100;
    freeList->nextShip = freeList2;
    freeList2->nextShip = freeList3;
    freeList3->nextShip = freeList4;
    freeList4->nextShip = NULL;
    printSpaceShip(freeList);
    cout << getLowestPower(freeList) << endl;
    removeSpaceShipPower(freeList, 75);
    printSpaceShip(freeList);
}

输出:

Spaceship #1 Power: 50 Health: 100
Spaceship #2 Power: 25 Health: 100
Spaceship #3 Power: 75 Health: 100
Spaceship #4 Power: 100 Health: 100
25
Spaceship #1 Power: 50 Health: 100
Spaceship #2 Power: 25 Health: 100
Spaceship #3 Power: 9310088 Health: 9306304

1 个答案:

答案 0 :(得分:0)

我稍微调整了你的代码来生成这个:

SpaceShip* removeSpaceShipPower(SpaceShip *x, int y)
{
    SpaceShip *current = x;
    SpaceShip *toDelete = NULL;
    SpaceShip *next = NULL;
    // check if head of list is to be deleted
    if (current->power == y) {
       next = current->nextShip;
       free(current);

       return next;
    } 

    while(current->nextShip != NULL)
    {
        if(current->nextShip->power == y)
        {
            toDelete = current->nextShip;           // remember this address for later
            next = current->nextShip->nextShip;
            current->nextShip = next;               // splice out the node to be deleted
            free(toDelete);                         // delete the spliced node
            return;
        }
        current = current->nextShip;
    }

    return x;
}

以下是您原始逻辑的错误:

next = current->nextShip->nextShip; // next is two steps ahead of current
current->nextShip = next;           // current->nextShip points two steps ahead
toDelete = current->nextShip;       // you are deleting the wrong node!
free(toDelete);

在图形方面,假设您有以下链接列表:

1 -> 2 -> 3 -> 4 -> 5

如果您尝试删除3,原始代码最终会以此结束:

1 -> 2 -> 3 -> NULL     -> 5 (dangling)

您看到随机整数的原因是您正在访问已释放的内存。您可能也会遇到分段错误。