c++ - 删除链表中的节点

标签 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,那么它应该删除链表中的所有元素,最后 head 也应该变为 NULL 这样如果我传递这个 head 来计算列表中的节点数它应该说是列表清空等类似的操作。

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

请建议修改,如果链接列表中所有节点的函数参数都具有相同的值,则 head 应变为 NULL。

最佳答案

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

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;
}

关于c++ - 删除链表中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10198129/

相关文章:

c++ - 如何简单地创建一个 ASN.1 DER 编码的 blob

c++ - 我如何拥有返回另一个对象指针的 getter?

c++ - 我如何使用 CMake 按需构建 wxwidgets 并与之链接

android - 如何使用 android ndk 的原生相机库?

java - 双向链表删除运行 O(n) 的索引处的项目?

c++ - 开始 c++ : OOP Methodologies and more

python - 斐波那契调用图中的值分区(调用图是二叉树)

algorithm - 根据高度安排足球队球员

mysql - 对现有复杂 MySQL 模式进行建模的最佳软件(或其他)解决方案

java - Java中具有连续整数键的高效元素映射