【问题标题】:Reversing Linked List - C++反转链表 - C++
【发布时间】:2011-10-26 00:07:28
【问题描述】:

我写了一个可以反转列表的函数。

到目前为止,我只能反转两个项目,但不能再反转了。我检查并仔细检查,仍然找不到问题。我什至使用调试器查看每个指针的值。运行调试器时,我收到消息:

程序中出现访问冲突(分段错误)。

这是我的第一个链表作业,所以我还在学习。

这是我用 Dev-C++ 编写的代码:

List::ListNode *List::Reverse_List(ListNode *head)
{
    ListNode *cur = head;
    ListNode *forward = NULL;
    ListNode *previous = NULL;

    while (cur != NULL)
    {
        head = cur; //set the head to last node
        forward = head->next;  //save the next pointer in forward
        cur->next = previous;  //change next to previous
        previous = cur;
        cur = forward;

        cout << "cur= " << cur->item << endl; //this is just to display the current value of cur

        return head;
    }
}

【问题讨论】:

  • 成员函数返回的最后一个节点是什么?您如何将反向列表头节点的前一个元素设置为 NULL ?
  • 哎呀!我的错,我忘了返回 *head;我将编辑代码。谢谢。
  • 但是程序停止工作。我仍然无法找出问题所在。
  • 此外,在编译源代码后,我还收到消息:"[Linked error] undefined reference to 'WinMain@16' ID returned 1 exit status。我仍然找不到原因消息。
  • return head; 退出循环,它会在一次迭代后返回。向我们展示ListNode 的声明,如果每个节点都存储一个next 和一个previous 指针,那么它会相当简单。

标签: c++ function pointers


【解决方案1】:

您的代码已关闭,它会提前返回。

List::ListNode *List::Reverse_List(ListNode *head) 
{
    ListNode *cur = head;
    ListNode *forward = NULL;
    ListNode *previous = NULL;

    while (cur != NULL) {
        //There is no need to use head here, cur will suffice
        //head = cur; //set the head to last node
        forward = cur->next; //save the next pointer in forward

        cur->next = previous; //change next to previous
        previous = cur;
        cur = forward;

        cout << "cur= " << cur->item << endl; //this is just to display the current value of cur

        //don't return here you have only adjusted one node
        //return head;
    }

    //at this point cur is NULL, but previous still holds the correct node
    return previous;
}

【讨论】:

  • 即使我使用上面的代码,我仍然遇到同样的问题:我无法获得超过 2 个项目的反向列表。并且程序自发停止。我仍在试图弄清楚,但是,什么都没有出来。
  • 我怀疑程序停止运行,因为我有这个错误 [链接器错误] 未定义对 WinMain@16 Id 的引用返回 1 退出状态。在这一个上,我仍然无法弄清楚问题。
  • 如果您遇到链接器错误,那么您实际上并没有运行您更改的代码,您正在运行上次成功构建时构建的任何内容。
【解决方案2】:

今天每个人都必须有相同的家庭作业。

我认为向这些人展示列表在反转时会发生什么情况会更有帮助。这应该比向他们展示代码或代码问题更好地帮助他们。

这是应该发生的事情(使用我将使用的算法)

[] = 头部 () = 当前

([1])->2->3->4, [2]->(1)->3->4, [3]->2->(1)->4, [4]->3->2->(1) 完成,因为当前没有新的下一个

【讨论】:

    【解决方案3】:

    很抱歉回答晚了,我相信您现在已经找到了答案,但它可能对其他人有所帮助。答案只是将 return 语句(即 return head;)从 while 循环中取出来解决你的问题。尽管有一些方法可以避免额外的指针和赋值来优化代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-30
      • 2016-03-19
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多