gpt4 book ai didi

c - 从动态链表中删除节点

转载 作者:太空宇宙 更新时间:2023-11-04 07:12:48 25 4
gpt4 key购买 nike

我正在编写一个程序,将字符串保存到链表中,同时为字符串和节点分配内存。我的插入和搜索功能运行良好,但删除功能似乎无法正常运行。它似乎并没有从节点中删除信息,但我不知道该设置什么以及要释放什么。任何帮助都将非常受欢迎,即使只是一个提示。

我的节点和列表结构

typedef struct listNode {               //simple linked list   structure
struct listNode *next; //address to next
char *data; //data
} NODE;

typedef struct ListStruct {
NODE *head; //head node for iterating
} LIST;

这是我当前删除节点的非工作版本

void deleteNode(LIST *list, char *string){          // passed linked list and string to find
NODE *prev, *curr, *temp; //variables init
//int compare; // for strcmp if needed
prev = NULL; //set prev to null
curr = list->head; //set current to the head of the list
while(curr != NULL){ //while the current node is not null
if(strcmp(curr->data,string) == 0){ //check for the proper string
temp = curr; //set temp to current node to be deleted
temp->data = strcpy(curr->data); //copy data so free is possible
prev->next = temp; //set the prev to temp
free(curr->data); //free malloc'd data
free(curr); //free malloc'd node
curr = temp; //set curr back to temp
}
else{ //if string isn't found at current
prev = curr; //set previous to current
curr = curr->next; //and current to current.next
}

}
}//done

我知道错误是在我找到正确的字符串时出现的,但我终究无法找出问题所在。希望很快收到某人的来信,一如既往地感谢你。

最佳答案

你可能想稍微更新一下 if block :

if(strcmp(curr->data,string) == 0){         //check for the proper string 
temp = curr; //set temp to current node to be deleted
if (prev == NULL) // if the first node is the one to be deleted
list->head = curr->next;
else
prev->next = curr->next; //set prev next pointer to curr next node
curr = curr->next; //curr updated
free(temp->data); //free malloc'd data
free(temp); //free malloc'd node

break; //assume there is only one unique string in the link list
}

关于c - 从动态链表中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27072901/

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