删除链接列表中的节点

时间:2012-04-17 19:49:59

标签: c++ data-structures

这是我删除所有在参数中传递了值的节点的代码。

typedef struct nodetype
{
    int data;
    struct nodetype * next;
} node;

typedef node * list;


void Linklist::deleteNode(list * head, int value)
{

    list current = *head;
    list previous = *head;
    while(current != NULL)
    {
        if(current->data != value)
        {
              previous = current;
              current = current->next;
        }

        else if (current->data == value)
        {
            previous->next = current->next;
            delete current;
            current = previous->next;

        }
    }
} 

但是如果链接列表中的所有元素都是2,那么它应该删除linklist中的所有元素,最后head也应该变为NULL,这样如果我通过这个头来计算列表中的节点数应该说列表是空的和其他类似的操作。

根据我目前的实现,对于上述情况,头部不会变为NULL。

请建议修改,以便在linklist包含函数参数中传递的相同值的所有节点时,head应该变为NULL。

1 个答案:

答案 0 :(得分:2)

我修改了我的代码,现在修改了它的工作文件

void Linklist::deleteNode(list *head, int value)
{

    list * current = head;
    list * previous = head;
    bool flag = false;
    while(*current != NULL)
    {
        if((*current)->data != value)
        {
            *previous = *current;
            *current = (*current)->next;
        }

        else if ((*current)->data == value)
        {
            flag = true;
            (*previous)->next = (*current)->next;
            delete *current;
            *current = (*previous)->next;

        }
    }
    if(!flag)
        cout<<"Element not found in the linklist\n";
    cout<<"Count is "<<Linklist::count(*head)<<endl;
}
相关问题