如何删除双重链接列表中所有出现的特定字符?

时间:2019-02-26 10:32:10

标签: c pointers linked-list doubly-linked-list

我可以知道为什么我的代码不起作用吗? if循环中的逻辑似乎很合理,因此我认为错误可能是在外部for循环中出现,或者我没有返回修改后的列表。

struct list* delete_char(struct list* the_list, char value){
    struct list *copy1 = the_list;
    struct list *copy2 = the_list;
    struct list *copy3 = the_list;
    int i = 0;

    for (copy1; copy1 -> info != value; copy1 = copy1 -> next){
        if (copy1 -> info == value){
            copy2 = copy1 -> next;
            copy3 = copy1 -> prev;
            copy3 -> next = copy2;
            copy2 -> prev = copy3;
            i ++;
        }
        if (copy1 -> prev == NULL && copy1 -> info == value){
            copy2 = copy1 -> next;
            copy2 -> prev = NULL;
            i++;
        }
        if (copy1 -> next == NULL && copy1 -> info == value){
            copy2 = copy1 -> prev;
            copy2 -> next = NULL;
            i++;
        }
    }

    if (i == 0){
        printf("The element is not in the list!\n");
    }

    return the_list;
};

1 个答案:

答案 0 :(得分:1)

乍一看,我看到两个问题:

  • for (copy1;应该是什么意思? GCC发出statement with no effect警告。
  • 循环中的第一个if条件永远不能为TRUE,因为它与循环条件相反。

如果我正确理解了您的描述

  • 遍历列表
  • 删除任何info == value
  • 处的条目
  • 在列表中未找到value时打印一条消息
  • 返回列表的(可能更新的)标题

这是我编写此函数的方式。由于您的问题不包含struct list的定义,因此我进行了有根据的猜测:

struct list {
  char info;
  struct list* prev;
  struct list* next;
};

struct list* delete_char(struct list* the_list, char value) {
  struct list* entry = the_list;
  unsigned int count = 0;

  while (entry) {
    /* entry may be removed during this iteration */
    struct list* next = entry->next;

    if (entry->info == value) {
      struct list* prev = entry->prev;

      /* value found */
      count++;

      /* unchain entry from list */
      if (prev) {
        /* not removing first entry on the list */
        prev->next = next;
      } else {
        /* removing first entry on the list: new head of list */
        the_list = next;
      }
      if (next) {
        /* not removing last entry on the list */
        next->prev = prev;
      }

      /* delete entry */
      free(entry);
      /* NOTE: entry is now invalid! */
    }

    entry = next;
  }

  if (!count) {
    printf("The element is not in the list!\n");
  }

  return the_list;
}