在C ++中从双向链表中删除重复项

时间:2015-09-30 14:23:55

标签: c++

在页面上运行时运行正常,但是当我尝试在C ++中运行该代码时,它会抛出异常“访问违规读取位置”,有人请帮助我......

void dll::compress(){
    Node *temp1, *temp2, *dup;
    temp1 = head;

    while (temp1 && temp1->next)
    {
        temp2 = temp1->next;

        while (temp2)
        {
            if (temp1->data == temp2->data)
            {
                dup = temp2;
                if (temp2->next != NULL){
                    temp2 = temp2->next;
                    temp2->prev = temp1;
                    temp1->next = temp2;
                    delete dup;
                }
                else {
                    temp1->next = NULL;
                    delete temp2;
                }
            }
            else
            {
                temp2 = temp2->next;
            }
        }
        temp1 = temp1->next;
    }
}

1 个答案:

答案 0 :(得分:1)

delete temp2;之后,您会继续循环,但temp2NULL且无效。

您需要将其设置为NULLbreak