递归反转单链表的函数中的分段错误
我正在实现一个函数来递归地反转链表,但出现段错误。
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。
谢谢大家:)
I am implementing a function to recursively reverse a linked-list, but getting 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;
}
Can you please help?
P.S. The iterative version is working fine though. Its not homework. Just practicing C.
Thank you all :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一般的递归算法是:
将列表分为
2
部分 - 首先节点和列表的其余部分。
链接列表。
rest
链接到first
。head
指针您正确执行了步骤 1 和 2,但我猜您在步骤 3 和 4 中搞砸了。我建议您尝试以下操作:
(来源:geeksforgeeks.org)
。
编辑:
PS:我还没有测试过这个。因此,请尝试一下并让我们知道:)我已经测试了上述功能,并且似乎按预期工作。您可以在这里尝试该程序:
http://ideone.com/bQXAV
The general recursive algorithm for this is:
Divide
the list in2
parts - firstnode and rest of the list.
rest
of thelinked list.
rest
tofirst
.head
pointerYou are doing steps 1 and 2 correctly but I guess you've messed up in steps 3 and 4. I would suggest you try this:
(source: geeksforgeeks.org)
.
EDIT:
PS: I've not tested this. So try it and let us know :)I've tested the above function and seems to work as expected. You can try the program here:
http://ideone.com/bQXAV
@Unicornaddict 已经发布了正确的算法。
但是,如果您仍然遇到分段错误,我怀疑您在从 main 调用函数时犯了一些错误。
正确:
解释:
head->next
传递给递归函数。如果你传递head
,它会做类似的事情这将使
head
指向NULL
和A
指向head
将head->next
作为参数传递后,列表的状态为:所以,你需要让
head
指向rest
(C
在这种情况下)。@Unicornaddict has already posted a correct algorithm.
But, if you are still getting
segmentation fault
, I suspect you are making some mistake in calling the function frommain
.Correct:
Explanation:
head->next
to the recursive function. If you passhead
, it will do something likewhich will make
head
point toNULL
andA
point tohead
head->next
as argument, state of the list is:So, you need to make
head
point torest
(C
in this case).你的算法似乎是错误的。您需要将指针返回到新列表的头部,但您正在将指针返回到最后一项。
事实上,您可能需要它们两者:指向头部的指针和指向最后一项的指针。
Your algorithm seems to be wrong. You need to return the pointer to the head of the new list, but you are returning the pointer to the last item.
Indeed, you perhaps need both of them: a pointer to the head and the pointer to the last item.
我认为
应该是
i think
should be