[英]Segmentation fault in a function to reverse a singly linked list recursivley
我正在實現一個遞歸反轉鏈表的函數,但是遇到了seg-fault。
typedef struct _node {
int data;
struct _node *next;
} Node, *NodeP;
NodeP recursiveReverseList(NodeP first){
if(first == NULL) return NULL;
if(first->next == NULL) return first;
NodeP rest = recursiveReverseList(first->next);
rest->next = first;
first->next = NULL;
return first;
}
你能幫忙嗎?
PS迭代版本工作正常。 它不是功課。 只是練習C.
謝謝你們 :)
一般的遞歸算法是:
Divide
列表中的2
件-第一節點和列表的其余部分。 rest
。 rest
鏈接到first
。 head
指針 你正在正確地做第1步和第2步,但我猜你已經搞砸了第3步和第4步。我建議你試試這個:
NodeP recursiveReverseList(NodeP first){
if(first == NULL) return NULL; // list does not exist.
if(first->next == NULL) return first; // list with only one node.
NodeP rest = recursiveReverseList(first->next); // recursive call on rest.
//rest->next = first; CHANGE THIS
first->next->next = first; // make first next to the last node in the reversed rest.
first->next = NULL; // since first is the new last..make its next NULL.
//return first; CHANGE THIS
return rest; // rest now points to the head of the reversed list.
}
(來源: geeksforgeeks.org )
。
編輯:
PS:我沒試過這個。 所以嘗試一下,讓我們知道:)
我測試了上面的功能,似乎按預期工作。 你可以在這里試試這個程序: http : //ideone.com/bQXAV
@Unicornaddict已經發布了正確的算法。
但是,如果你仍然遇到segmentation fault
,我懷疑你在從main
調用函數時犯了一些錯誤。
head->next = recursiveReverseList(head->next);
head->next
遞歸函數head->next
。 如果你通過head
,它會做類似的事情 來電前:
頭---> A ---> B ---> C.
通話后:
頭<--- A <--- B <--- C.
這將使head
指向NULL
和A
指向head
head->next
作為參數后,列表的狀態為: 頭---> A <--- B <--- C.
所以,你需要讓head
rest
(在這種情況下為C
)。
你的算法似乎是錯誤的。 您需要將指針返回到新列表的頭部,但是您將指針返回到最后一個項目。
實際上,您可能需要它們兩個:指向頭部的指針和指向最后一個項目的指針。
我認為
rest->next = first;
應該
first->next->next = first;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.