我试图在一个函数中删除链表中的所有特定关键元素。
那就是如果链表有1 2 2 3 4 4 5 5 8 2 6 32 4 6 7 7然后我通过函数2该函数删除链表中的所有2

我的链表在这里

class float_list
{
     struct node
    {
        double data;
        struct node *next;
     };
        node *head;
public:

    float_list(void)
    {
        head = nullptr;
    };

    void appendNode(double);
    void print_list();
    void deleteNode(double);

};

现在我的deleteNode(double在这里)
void float_list::deleteNode(double num)
{
    node *nextptr, *previousptr = nullptr;
    nextptr=head;
    if(!head->data){return;}
    if(head->data==num)
    {
        nextptr= head->next;
        delete head;
        head = nextptr;
    }
    else
        while(nextptr)
        {
            previousptr= nextptr;
            if(nextptr->data==num)
            {
                previousptr->next = nextptr->next;
                delete nextptr;
                cout<<"I Found the  --> "<<num<<"  is going to be deleted"<<endl;
                nextptr = previousptr;
                //nextptr = nextptr->next;
            }
            nextptr = nextptr->next;
        }
        delete nextptr;
        delete previousptr;
}

我以各种不同的方式尝试过,但始终会遇到访问冲突错误。如果可能的话,请给我概念和代码提示。谢谢
该代码在win32 Vs2010应用程序中

最佳答案

while循环结束后会发生什么。好吧,nextptr == NULL。删除NULL ==问题。

试试这个:

node *previous = nullptr, *current = head, *temp;

while(current){
    temp = current->next;
    if(abs(current->data - num) < MARGIN_OF_ERROR){
        if (previous){
            previous->next = current->next;
        } else {
            head = current->next;
        }
        delete current;
    } else{
        previous = current;
    }
    current = temp;
}

关于c++ - 删除在链表中找到的所有特定键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9442649/

10-15 17:56