我想知道为什么传递第二个参数 Node** fhead
会导致段错误? Node
有一个 int
值和一个指向下一个 Node
的 next 指针。
这是我的代码:
void reverse(Node* head, Node** fhead) {
if (!head->next)
{
fhead = &head;
return;
}
reverse(head->next, fhead);
head->next->next = head;
head->next = 0;
}
int main()
{
Node a = {1, 0};
Node b = {2, &a};
Node c = {3, &b};
Node** fhead;
reverse(&c, fhead);
}
最佳答案
你在递归终止时有一点错误。您应该将 *fhead
设置为 head
而不是用 &head
分配它(这只会在本地更改 fhead
功能):
if (!head->next)
{
*fhead = head;
return;
}
关于c++ - 递归反转没有全局变量的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34227345/