我正在使用链表编写一个简单的字典程序。我想在字典中搜索一个单词并将其删除。我已经编写了代码,但我认为这更耗时,因为我正在运行循环两次,第一次搜索节点并记下位置,第二次删除它。
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");
}
有没有其他方法来优化程序?
答案 0 :(得分:1)
你必须像这样将两个周期合并在一起,这里是一个代码示例。
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;
}
}