[英]How to delete all occurrences of a specific char in a double 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;
};
乍一看,我看到了两个问题:
for (copy1;
应该是什么意思?GCC 抛出一个statement with no effect
警告的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.