我已经完成了这段代码来从列表中删除一个元素:
列表结构:
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),除了我想要删除的元素。
我现在的问题是:
- 如何从旧列表(list)中删除所有元素?
- 如何将新列表 (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/