我能知道为什么我的代码不起作用吗? 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;
应该是什么意思?海湾合作委员会抛出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;
}