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

问题描述 投票:1回答:1

我能知道为什么我的代码不起作用吗? 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;
};
c pointers linked-list doubly-linked-list
1个回答
1
投票

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

  • 什么是for (copy1;应该是什么意思?海湾合作委员会抛出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;
}
© www.soinside.com 2019 - 2024. All rights reserved.