【发布时间】:2015-08-29 06:55:03
【问题描述】:
我无法理解反转链表的算法如何修复头指针。
void recursiveReverse(struct node** head_ref)
{
struct node* first;
struct node* rest;
/* empty list */
if (*head_ref == NULL)
return;
/* suppose first = {1, 2, 3}, rest = {2, 3} */
first = *head_ref;
rest = first->next;
/* List has only one node */
if (rest == NULL)
return;
/* reverse the rest list and put the first element at the end */
recursiveReverse(&rest);
first->next->next = first;
/* tricky step -- see the diagram */
first->next = NULL;
/* fix the head pointer */
*head_ref = rest;
}
在那之前我都明白了,这是我没有明白的最后一行。
如果列表是 1->2->3。所以,recursiveReverse(2) 会将 *head_ref 设置为 3。但是当它返回 recursiveReverse(1) 时,这里的 rest 指向 2。所以不应该将 *head_ref 设置为 2,(这是不正确的)但它没有实际上。这是如何工作的?
【问题讨论】:
-
请记住,在递归调用中,变量
head_ref实际上是您传递给递归调用的参数&rest。我建议您在调试器中运行,并逐行逐行执行代码,并单步执行每个递归调用。对于三个或四个节点的小列表,它非常快,应该会给你更多的洞察力。
标签: c algorithm recursion linked-list reverse