gpt4 book ai didi

c - 从链表中搜索并删除节点

转载 作者:行者123 更新时间:2023-11-30 14:56:59 25 4
gpt4 key购买 nike

我正在使用链表编写一个简单的字典程序。我想在字典中查找一个单词并将其删除。我已经编写了代码,但我认为这更耗时,因为我运行循环两次,第一次搜索节点并记下位置,第二次删除它。

struct node{
char word[20];
char meaning[5][100];
struct node *next;
};

void del(struct node *head, char *word)
{
int found = 0, position = 0, i;
struct node *temp = head;
while(temp != NULL)
{
if(strcmp(temp->word, word) == 0)
{
found = 1;
break;
}
temp = temp->next;
position++;
}
if(found == 1)
{
temp = head;
if(position == 0)
{
head = temp->next;
free(temp);
}
for(i = 0; i < position-1; i++)
temp = temp->next;
struct node *temp2 = temp->next;
temp->next = temp2->next;
free(temp2);
printf("Word deleted..\n");
}
else printf("Word not found!\n");
}

有没有其他方法可以优化程序?

最佳答案

您只需像这样将两个周期合并在一起,这是一个代码示例。

struct node{
char word[20];
char meaning[5][100];
struct node *next;
};

struct node *del(struct node *head, char *word)
{int found = 0, position = 0, i;
struct node *temp = head;
struct node *prev = NULL;
/*You should avoid breaks because they decrease legibility*/
while(temp != NULL)
{

if(strcmp(temp->word, word) == 0)
{
if(prev == NULL){ /*If the node is the head*/
head = head->next;
free(temp);
return head;
}else{
prev->next = temp->next;
free(temp);
return head;
}
}
prev = temp;
temp = temp->next;
}

}

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

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