【问题标题】:Why this function is not able to reverse the linked list using recursion? [closed]为什么这个函数不能使用递归来反转链表? [关闭]
【发布时间】:2022-10-14 19:11:32
【问题描述】:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverse(ListNode *prev,ListNode* curr,ListNode* future,ListNode *temp)
    {
        if(future==NULL)
        {
            *temp=*curr;
            return NULL;
        }
        reverse(curr,curr->next,future->next,temp);
        future->next=curr;
        cout<<future->val<<" "<<curr->val;
        return temp;
    }
    ListNode* reverseList(ListNode* head) {
        ListNode* temp=new ListNode(0);
        if(head==NULL)
        {
            return NULL;
        }
        return reverse(NULL,head,head->next,temp); 
    }
};

【问题讨论】:

  • 这是因为代码没有意义。
  • 关于成为精英 C++ 大师的秘密捷径有一个流行的神话:扔掉你的 C++ 教科书;而是做随机编码谜题,否则它们没有内在的学习价值,除了不良的编程习惯外,它们不会教任何东西。这个神话来自许多点击诱饵网站,它们承诺做他们的谜题会将任何人变成即时的 C++ 超级黑客。每个人最终都意识到这些编码难题是多么无用,但只有在浪费大量时间做一个又一个编码难题之后。他们没有什么可证明的。

标签: c++ recursion linked-list singly-linked-list function-definition


【解决方案1】:

提供的代码没有意义。

要反转列表,您不应分配新节点。

此外,当例如最初传递的列表为空时,您的代码可能会产生内存泄漏

ListNode* reverseList(ListNode* head) {
    ListNode* temp=new ListNode(0);
    if(head==NULL)
    {
        return NULL;
    }
    return reverse(NULL,head,head->next,temp); 
}

由于这条线

    ListNode* temp=new ListNode(0);

或者例如这个代码sn-p

    if(future==NULL)
    {
        *temp=*curr;
        return NULL;
    }

当列表仅包含一个节点时返回NULL,而不是返回指向该单个节点的指针。

而函数reverse的参数太多

ListNode* reverse(ListNode *prev,ListNode* curr,ListNode* future,ListNode *temp);

此外,成员函数应声明为类的静态成员函数。

该函数可以通过以下方式定义

static ListNode * reverseList( ListNode *head ) 
{
    if (head and head->next)
    {
        ListNode *current = head;

        head = reverseList( head->next );

        current->next->next = current;
        current->next = nullptr;
    }

    return head;
}

【讨论】:

    猜你喜欢
    • 2019-08-13
    • 1970-01-01
    • 2022-01-23
    • 2021-05-31
    • 2011-01-05
    • 2023-03-27
    • 2019-03-02
    • 2023-03-17
    • 2019-10-31
    相关资源
    最近更新 更多