我想遞歸刪除鏈接列表。我想到了如何迭代地做到這一點,但我很好奇如何做到這一點。到目前爲止,我有:以遞歸方式刪除指定數據的鏈接列表
void deleteNodeRecursively(LinkedList *list, int value){
Node *curr=list->head;
if (list->head==NULL){
return;
}
else if (list->head->data==value){
Node *x=list->head->next;
delete list->head;
list->head=x;
}
else{
LinkedList *newlist;
newlist->head=list->head->next;
deleteNodeRecursively(newlist,value);
}
}
哪裏定義
struct LinkedList{
Node *head;
};
struct Node{
int data;
Node *next;
};
我可以刪除頭如果需要的話,但我無法弄清楚如何清除體內或反面,然後正確地縫合起來該列表,更不用說遞歸地進行。我如何繼續?爲什麼這不工作?
編輯:刪除問號,並代之以我認爲會工作的代碼。
首先,您需要一個遞歸算法,然後才能匹配一個函數。提示:它可能需要一個'Node **'和'int'參數。 – WhozCraig
如果您有問號,爲什麼不能將deleteNodeRecursively(&list,value)並最終在null時返回?看起來你有基本情況和「所有其他情況」,只需要繼續調用它 –
當然,我不能這樣做,因爲只是回想起我的功能會一遍又一遍地檢查相同的頭節點。 –