【发布时间】:2017-07-28 02:45:05
【问题描述】:
这是我要问的同一个问题: deleting even nodes from a doubly link list c++
不同之处在于,我想了解我的代码有什么问题。我不想在不理解我的代码为什么不起作用的情况下就接受完全不同的方法。这是我的代码的两个版本,我想知道两者都有什么问题。他们都给我分段错误。
int removeEven(node *&head)
{
if(!head) //Base case: end of list reached
return 0;
int count = removeEven(head->next); //Recurse to end of list
if(head->data % 2 != 0)
return count;
else{
++count;
if(head->next){
head->next->previous = head->previous;
}
if(head->previous){
head->previous->next = head->next;
} if(!(head->previous)){
node* temp = head;
head = head->next;
delete temp;
}
else
delete head;
}
return count;
}
第二个将 count = 0 作为默认参数。
int removeEven(node *&head, int count)
if(head && head->data % 2 != 0) //not null, not even
{
removeEven(head->next, count);
}
else if(head != NULL){ //not null, yes even
++count;
if(head->next)
head->next->previous = head->previous;
if(head->previous)
head->previous->next = head->next;
node* temp = head;
head = head->next;
delete temp;
removeEven(head, count);
}
return count; //base case: null
}
【问题讨论】: