【问题标题】:Deleting elements from linked lists in C?从C中的链表中删除元素?
【发布时间】:2021-03-26 04:39:21
【问题描述】:

所以我知道我必须做什么的背景。将前一个元素链接到下一个元素。但无论我尝试什么,我都会遇到分段错误(LINUX GCC)。所以有人可以看到我做错了什么。打印功能工作正常,因此故障必须在功能中的某个地方。代码如下...

定义...(编辑) 对不起,现在发布声明...

    typedef struct Word {
        char *word;
        int count;
        struct Word *next;
    } Word;

    typedef Word* Dictionary;

void delete_word (Dictionary dict, char* str){
    Dictionary tempprev=dict;
    dict=dict->next;
    Dictionary tempnext=dict->next;
    while (dict!=NULL){
        if (strcmp(dict->word,str)==0){
            tempprev->next=tempnext;
            free (dict->word);
        }
        tempprev=dict;
        dict=dict->next;
        tempnext=dict->next;
    }
}

【问题讨论】:

  • 用笔和纸画出指针。
  • @Đugum Roko 至少显示名称 Dictionary 是如何定义的。
  • 绘制带有一些方框和箭头的图表真的很值得。此外,作为一般偏好,我发现将指针隐藏在 typedef always 后面会使事情变得混乱。尤其是当你可能需要一个指向指针的时候,以防你移除头部......
  • 关于:dict=dict->next; .... while (dict!=NULL){ 如果链表包含 0 个条目,那么这是访问内存地址 0 的正上方。结果将是段错误事件
  • 请发minimal reproducible example,以便我们重现问题并帮助您调试。

标签: c struct linked-list singly-linked-list function-definition


【解决方案1】:

您没有说明名称字典是如何定义的。考虑到提供的函数,名称 Dictionary 似乎是一个表示指针的 typedef 名称。

如果是这样,那么函数可以通过以下方式声明和定义

void delete_word( Dictionary *dict, const char *word )
{
    while ( *dict )
    {
        if ( strcmp( ( *dict )->word, word ) == 0 )
        {
            Dictionary current = *dict;
            *dict = ( *dict )->next;
            free( current );
        }
        else
        {
            dict = &( *dict )->next;
        }
    }
} 

如果你主要有一个类型为Dictionary 的指针

Dictionary dict;

然后调用函数就像

delete_word( &dict, word );

如果列表只能包含一个带有给定单词的节点,那么函数定义可以如下所示

void delete_word( Dictionary *dict, const char *word )
{
    while ( *dict && strcmp( ( *dict )->word, word ) != 0 )
    {
        dict = &( *dict )->next;
    }

    if ( *dict )
    {
        Dictionary current = *dict;
        *dict = ( *dict )->next;
        free( current );
    }
} 
        

【讨论】:

  • @ĐugumRoko 这个数据成员int count;没有意义。无论如何,我展示了如何定义函数。
  • 计算单词重复显示,与此功能无关。
猜你喜欢
  • 2020-09-04
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
  • 2020-10-29
  • 1970-01-01
  • 2018-08-30
  • 1970-01-01
相关资源
最近更新 更多