首页 > 解决方案 > 从C中的链表中删除元素?

问题描述

所以我知道我必须做什么的背景。将前一个元素链接到下一个元素。但无论我尝试什么,我都会遇到分段错误(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;
    }
}

标签: cstructlinked-listsingly-linked-listfunction-definition

解决方案


您没有显示名称 Dictionary 是如何定义的。考虑到提供的函数,该名称似乎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 );
    }
} 
        

推荐阅读