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

标签 c dictionary linked-list

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

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/

相关文章:

c - 对链表进行基数排序

c - 你知道为什么 BMI 值的输出总是 0.0000 吗?

iphone - NSCharacter Set 使用 int,但我需要未分配的短字符?

ios7 - iOS 7 上的 Swift 字典

ios - 如何快速过滤字典并将结果输出到 CollectionViewController

ios - viewForAnnotation 没有被调用

c - 理解 C 中的函数和指针

c - 需要有关基本 ASM 的帮助

c - 无法打印列表的最后一个元素

c - C 中的链表、结构的结构、段错误