c - 从列表中删除元素 C

标签 c

我已经完成了这段代码来从列表中删除一个元素:

列表结构:

typedef struct list_t{
  struct node_t *head;
  int size;
};

typedef struct node_t{
  struct entry_t *element;//Each entry has a key
  struct node_t *next;
}node_t;

删除方法:

int list_remove(struct list_t *list, char *key){
  node_t *no = list->head;
  struct list_t *lista = list_create();
  int i;
  for(i=0;i<list->size;i++){
    if(strcmp(no->element->key, key)==0)
      no=no->next;
    else {
      list_add(lista,no->element);
      no=no->next;
    }
  }
}

列表中的每个元素都有一个键。

我的想法是使用给定列表(list)中的元素创建一个新列表(lista),除了我想要删除的元素。

我现在的问题是:

  1. 如何从旧列表(list)中删除所有元素?
  2. 如何将新列表 (lista) 中的元素添加到旧列表 (list) 中?

谢谢。

最佳答案

这是就地删除链表中节点的标准方法。希望这对您有用:

int list_remove(struct list_t *list, char *key) {
  node_t *node = list->head;
  node_t *prev = NULL;   //to keep track of the previous node
  int i;
  for(i=0; i<list->size; i++) {
    if(strcmp(node->element->key, key)==0) {
      if(node == list->head) {   //if 1st node has to be deleted
        if(list->size == 1)    //if there's only one node in list
          list->head = NULL;
        else
          list->head = node->next;
        list->size--;
        return 0;
      }
      prev->next = node->next;
      return 0;
    } else {
      prev = node;
      node=node->next;
    }
  }
  return -1;
}

关于c - 从列表中删除元素 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17772684/

相关文章:

c++ - 释放双指针上的内存

TensorFlow 中 C 代码的代码完成

c++ - 获取国家域名

c - 为什么我能够在此 char 数组中存储的字节数比使用 malloc() 提供的字节数多?

C 复制到两个缓冲区中,尽管应该只填充一个缓冲区

c - 迭代未知长度的 int 数组

c - 作为变量和值传递的参数,都返回不同的答案

c - 我的程序中颠倒字符串中单词的顺序有什么问题?

python - 记录由 C API 生成的 Python 模块的最佳方法?

c++ - 使用 gammu 时自动检测调制解调器端口