我试图编写一个删除链接列表中具有给定值的所有节点的函数,但我想尝试使用递归函数。我认为删除列表中最后一个节点的代码块无意中将整个列表设置为null,但我不知道如何解决这个问题。
编辑:整个列表不应该为空,它应该删除包含给定整数的所有节点。例如,如果给定列表是3-> 4-> 3-> 6并且我们想删除3的所有实例,则列表将是4-> 6
typedef struct nodeStruct {
int num;
struct nodeStruct *next;
struct nodeStruct *prev;
}node;
node* deleteNode(node* head, int num) {
node* current = head;
if (current == NULL) {
return head;
} else if (current->num == num) {
if (current->prev == NULL) {
head = current->next;//delete first Node
head->prev = NULL;
free(current);
head = deleteNode(head, num);
} else if (current->next == NULL) {
free(current);//delete last node
return head;
} else {
current->prev->next = current->next; //delete middle node
current->next->prev = current->prev;
free(current);
head = deleteNode(head, num);
}
} else {
head = deleteNode(current->next, num);
}
return head;
}
答案 0 :(得分:1)
类似这样的事情
if(head == NULL){
return NULL;
} else {
node *rest = deleteNode(head->next, num);
if(head->num == num){
if(rest != NULL){
rest->prev = NULL;
}
free(head);
return rest;
} else {
if(rest != NULL){
rest->prev = head;
}
head->next = rest;
return head;
}
}