是的 - 你的逻辑有点错误。改变 head 的值会破坏算法。这个想法是,在每次返回后,head 和 link 都会恢复它们的旧值。
试试:
void Reverse(Node* head) // Just pass a pointer
{
if (head == NULL)
return;
Node *link = head->next;
if (link == NULL)
return;
Reverse(link);
link->next = head;
head->next = NULL;
// head = link; Don't change head
}
但这还是有一个问题——列表反转后如何设置新的头部?您需要捕获指向原始列表中最后一个元素的指针。
像这样改变:
void Reverse(Node* p, Node** newHeadAddr)
{
// Will only happen if list is empty
if (p == NULL) return;
Node *link = head->next;
// If the end is reached
if (link == NULL)
{
*newHeadAddr = p;
return;
}
Reverse(link, newHead);
// link now points to last element in reversed list
// p points to current element
// so add p to the reversed linked list
link->next = p;
p->next = NULL;
}
并像这样使用它:
Node* newHead = nullptr;
Reverse(head, &newHead);
head = newHead;
关于逻辑:下面是递归调用进行时变量行为的示例,即每次调用时 p 和 link 指向的内容的描述。希望对您有所帮助。
假设您有一个包含三个元素的列表。
第一次通话时:
First call:
p is a pointer element[0] (i.e. head)
link is a pointer to element[1]
第二次通话时:
Second call:
p is a pointer to element[1]
link is a pointer to element[2]
---------------------------------------
First call:
p is a pointer to element[0] (i.e. head)
link is a pointer to element[1]
在第三次通话时:
Third call:
p is a pointer to element[2]
link is a null pointer
---------------------------------------
Second call:
p is a pointer to element[1]
link is a pointer to element[2]
---------------------------------------
First call:
p is a pointer to element[0] (i.e. head)
link is a pointer to element[1]
由于链接为 nullptr,调用将返回并且您有:
Second call:
p is a pointer to element[1]
link is a pointer to element[2]
---------------------------------------
First call:
p is a pointer to element[0] (i.e. head)
link is a pointer to element[1]
现在代码可以做
link->next = p; // element[2]->next = element[1]
p->next = nullptr; // element[1]->next = nullptr;
原来有
element[2]->element[1]->nullptr
然后返回:
First call:
p is a pointer element[0]
link is a pointer to element[1]
现在代码可以做
link->next = p; // element[1]->next = element[0]
p->next = nullptr; // element[0]->next = nullptr;
所以你有
element[2]->element[1]->element[0]->nullptr
你就完成了。