【问题标题】:recursively reversing a linked list [duplicate]递归地反转链表[重复]
【发布时间】:2014-06-03 14:29:26
【问题描述】:

我正在尝试使用递归和下面的代码来反转链表

struct node* reverse_list(struct node *head)
    {
        struct node *temp=head,*rhead,*first;
        if (temp->next== NULL)
            return temp;
        else
        {
            first = head;
            rhead = reverse_list(temp->next);
            first->next = NULL;
            rhead->next = first;
            return rhead;
        }
    }

我找不到任何错误,但我仍然没有得到正确的输出。请帮助。

【问题讨论】:

  • -- 已删除 -- 抱歉,我的错误 另一个提示:告诉我们您的输出是什么,这样我们也更容易看到问题所在
  • @Pinna_be 该问题未标记C++。因此struct node 不等于node
  • @Pinna_be:如果没有typedef,则结构类型为struct tag。您可以在 C++ 中省略 struct 关键字,但在 C 中则不能。
  • 为什么要使用递归的方式?它基本上是将所有列表元素的指针多次复制到堆栈上。问题很简单,只需在修改引用时迭代列表即可。
  • @Veger:我已经有了使用迭代的解决方案,我正在尝试使用递归的解决方案

标签: c linked-list


【解决方案1】:

您需要 2 个连续节点才能递归执行:

struct node* reverse_list(struct node *head)
    {
       return reverse_list_prev(null, head);
    }

struct node* reverse_list_prev(struct node *prev, struct node *current)
    {
        if(null==current)
            return prev;
        struct node *tmp = current->next;
        current->next = prev;
        return reverse_list_prev(current, tmp);
    }

【讨论】:

    【解决方案2】:

    我觉得这条线不太适合我

         rhead->next = first;
    

    在我看来,它应该遍历到rhead 列表的末尾,而其中的tail 指向first

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 2017-06-22
      • 1970-01-01
      • 2012-11-05
      • 2018-12-03
      • 2020-10-02
      • 2010-09-26
      • 2012-12-14
      • 1970-01-01
      相关资源
      最近更新 更多