删除链表中具有特定值的所有节点 [英] Removing all nodes with a certain value in a linked list

查看:42
本文介绍了删除链表中具有特定值的所有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题是不言自明的.这是我为此目的编写的函数:

The title is pretty self explanatory. Here's the function I've written for this purpose:

void wipeLoneCells()
{
    cell *tmp;

    tail = head;
    while (1)
    {
        if (head == tail && !tail->flag)
        {
            head = head->next;
            free(tail);
            tail = head;
            continue;
        }

        tmp = tail->next;

/***/   if (tmp->next == NULL && !tmp->flag)
        {
            tail->next = NULL;
            free(tmp);
            break;
        }
        else if (!tmp->flag)
        {
            tail->next = tmp->next;
            free(tmp);
            continue;
        }

        tail = tail->next;      
    }
}

列表的头部和尾部是全局的,并且在调用此函数时构建列表,头部指向第一个节点,尾部指向最后一个节点(下一个为 NULL).我几乎可以肯定我的链接列表是正确构建的,因为我可以毫无错误地打印它们.有时此功能可以完美运行,有时会导致标有星号的行发生访问冲突.我知道这并不是完全错误,因为我确实在不产生错误时得到了我想要的结果,尽管我确实经常收到错误,所以一定有我忽略的东西.在此先感谢您的帮助.

The list's head and tail are global, and the list is built by the time this function gets called with head pointing to the first node and tail pointing to the last (whose next is NULL). I'm almost certain that my linked list is built correctly as I can print them with no errors. Sometimes this function works perfectly and sometimes it results in an access violation at the line marked with stars. I know it's not completely wrong as I do get the result I want when it doesn't produce an error, although I do get the error frequently so there must be something I'm overlooking. Thank you in advance for any help.

这是固定代码:

void wipeLoneCells()
{
    cell *tmp;

    tail = head;
    while (1)
    {
        if (head == tail && !tail->flag)
        {
            head = head->next;
            free(tail);
            tail = head;
            continue;
        }

        tmp = tail->next;

        if (tmp->next == NULL && !tmp->flag)
        {
            tail->next = NULL;
            free(tmp);
            break;
        }
        else if (tmp->next == NULL)
        {
            tail = tmp;
            break;
        }
        else if (!tmp->flag)
        {
            tail->next = tmp->next;
            free(tmp);
            continue;
        }

        tail = tail->next;      
    }
}

推荐答案

如果

tmp = tail->next; 

NULL 吗?下一行尝试取消引用 NULL 指针,这会导致 未定义行为 - 可能导致崩溃.

is NULL? The next line attempts to dereference a NULL pointer, which results in undefined behavior - possibly leading to a crash.

您应该检查这种情况并采取适当的措施.

You should check for this condition and take appropriate action.

这篇关于删除链表中具有特定值的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆