gpt4 book ai didi

c - 如何删除列表中的第一项?

转载 作者:行者123 更新时间:2023-11-30 15:42:05 25 4
gpt4 key购买 nike

我正在构建一个应该删除链接列表中的项目的函数。我的问题是我可以删除任何元素但不能删除第一个元素,这是为什么?

我的目标文件:

typedef struct list {
char *key;
char *value;
struct list *next;
} List;

void db_init(List *list) {
list = malloc(sizeof(db_sizeOfStruct()));

list->next = NULL;
list->key = NULL;
list->value = NULL;
}

void db_delete(char *key, List *list) {
List *prev;
db_init(prev);
int first = 1;

while(list != NULL) {
if(strcmp(key, list->key) == 0) {
if(first == 1) {
list = list->next; // This is supposed to delete the first item in the list but it does not work...
} else {
prev->next = list->next;
}
return;
} else {
prev = list;
list = list->next;
first = 0;
}
}
}

在程序的主文件中:

void delete(List *list) {
printf("key: ");
char *key;
key = malloc(sizeof(key)+1);
readline(key, 128, stdin);

if(key != NULL) {
db_delete(key, list);
}
}

int main(void) {
delete(list);
return 0;
}

最佳答案

这里有几个问题

首先,您调用 db_init,即使您想删除一个元素,它也会分配一个元素。

其次,您需要考虑到,如果第一个元素被删除,您需要返回新的第一个元素的地址,但使用当前的函数,您不会这样做。

原型(prototype)应该看起来像这样

void db_delete(char *key, List **list)

或者也许更简洁一点,通过返回第一个元素:

List* db_delete(char *key)

所以这个函数可能看起来像这样

List* db_delete(const char *key, List *list) 
{
// normally it is not a good idea to use an argument
// to a function as a loop variable in a function
// also check arguments to avoid segfaults and
// other headaches
if ( key != NULL && list != NULL )
{
List* cur = list;
List* prev = NULL;

for ( ; cur != NULL; cur=cur->next )
{
// identify if it is the one to delete
if ( !strcmp(key, cur->key) )
{
if ( prev != NULL ) // if not first
{
List* tmp = cur;
prev->next = cur->next;
free(tmp);
return list;
}
else // if first
{
List* tmp = cur;
List* next = cur->next;
free( tmp );
return next;
}
}
}
prev = cur;
}
return list;
}

另一个技巧是使用calloc而不是malloc,那么你就不需要需要初始化下一个、上一个,因为它们已经是 0。

关于c - 如何删除列表中的第一项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20323867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com