gpt4 book ai didi

c++ - 使用递归反转链表

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:59:23 25 4
gpt4 key购买 nike

我希望能够编写一个递归函数来反转链表。假设所有元素都已附加到列表中。

我想把head->next->next赋值给head,所以node->next的下一个节点就是节点本身。然后,当递归完成时,将链表的头(this->head)分配给最终节点(head)。

还缺少的是将最后一个节点的 next 分配给 NULL。

这样的东西在任何世界都行得通吗?它给出了运行时/段错误。

struct node {
int data;
node *next;
};

class LinkedList{
node *head = nullptr;
public:
node *reverse(node *head){
if(head->next != nullptr){
reverse(head->next)->next = head;
}
else{
this->head = head;
}
return head;
}
};

最佳答案

请注意,您忽略了 head 是 nullptr 本身的情况。此外,您不能只返回 head...您需要返回 reversed 列表的头部。

试试这个:

node* reverse_list(node* head) {
if (head == nullptr or head->next == nullptr) { return head; }
auto tail = head->next;
auto reversed_tail = reverse_list(tail);
// tail now points to the _last_ node in reversed_tail,
// so tail->next must be null; tail can't be null itself
tail->next = head;
head->next = nullptr;
return reversed_tail;
}

(未测试...)

关于c++ - 使用递归反转链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50656075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com