c - 从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;
}
}
解决方案
您没有显示名称 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 );
}
}
推荐阅读
- r - 在 R 中的列向量中检测和子集模式
- python - 在较大列表中的一个列表中查找特定的值序列
- python - 如何在 Redshift 中将十六进制数转换为二进制数?
- python - IfxPy - 使用带有 IfxPy 的 python 连接到 Informix 时出错
- android - 将图像文件从 Android 设备上传到 Laravel API
- selenium - Pyinstaller 包含用于 Firefox 的 selenium
- google-apps-script - 如何防止基于另一个值的单元格中的更改并显示有关尝试的警报框?
- nestjs - 是否可以使用范围为一的控制器/方法覆盖全局范围的警卫
- java - IntelliJ - Java 文件带有扩展名
- sidekiq - 无法成功禁用 Sidekiq 并发