【问题标题】:Reversing a Linked List with 2 pointers用 2 个指针反转链表
【发布时间】:2018-05-02 14:01:47
【问题描述】:

我正在尝试仅使用两个指针创建一个链表(我查看的每个帖子似乎都使用 3,但我对分配的要求是 2)

所以我将从我的处理方式开始。目前这些值是这样链接的 nullptr -> (head)1->2-> ... -> 7->8->nullptr,其中被反转的值是 1,2,3,4,5,6, 7,8

void reverseList(){
    ListNode *last = head;
    ListNode *current = last->next;

    if(current == nullptr) return;

    while(current != nullptr){
         current->next = last;
         last = current;
         current = last->next;
    }
}

从逻辑上讲,我的循环在纸上是有效的,但在我的 ide 和调试器中它是一个无限循环。

我还尝试创建一个循环来检查大小并从最后开始,其中 head = 8 和 tail = 1 但这也不起作用。

我还尝试了一种二分搜索方法,在该方法中找到了中点并执行了 +- mid 并进行了交换,但我也无法从 4->3 开始。

我的目标是从 1->2->3->4->5->6->7->8 到 8->7->6->5->4->3 ->2->1

【问题讨论】:

  • 用你的逻辑填写while循环,看看它是否有效。
  • 对不起!添加,我意识到一些可能有效但无限循环的东西,添加它
  • “逻辑上,在纸上我的循环可以工作” 你需要更好的逻辑或更好的纸。超越current 的唯一方法是采用原始current->next,但在查看之前将其覆盖。
  • 如果你有一个函数接受head 并且允许两个其他指针变量,那么你总共有三个。

标签: c++ pointers linked-list


【解决方案1】:

为了更简单,改为移动 head ptr。

因为您的display() 首先从head 开始。

void reverseList(){
    ListNode* current = head->next;

    if(current == nullptr) return; // list is empty

    head->next = nullptr;

    while(current != nullptr) { // have we reached the end of a forward list?
        ListNode* next = current->next;
        current->next = head; // reverse next pointer to "previous" node
        head = current;       // move last pointer to "current" node
        current = next;       // move to "next" node
    }
}

【讨论】:

  • 嗯,只打印出 2->nullptr;我对其进行了调试,但它进入了循环 3 次。
  • 感谢您的帮助!但它仍然做同样的事情。我只是想补充一点,我们不需要返回任何东西,因为它都是一个大类/结构的一部分。我正在尝试在我们说话时进行调试
  • 是的,我打印了原件。整个源码如下:pastebin.com/GEC0Un9d
  • 我刚刚检查了current的指针值,它在进行中,是我的显示功能吗?
  • 我在循环之前添加了 current->next = nullptr,在循环之后添加了 head = current 而不是 head->next = nullptr。这应该适用于我的显示器,但不能。真令人沮丧:
【解决方案2】:

当第一次进入循环时,电流指向'2'。然后会发生这种情况:

  • current->next get 被修改 (!) 为 head。

所以列表现在是 (head)1->2->(last==head)1->2->1->2->1 ...您已经创建了一个循环。这就是为什么你的程序永远不会终止的原因。

【讨论】:

    猜你喜欢
    • 2020-09-02
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2023-03-27
    • 2021-09-25
    相关资源
    最近更新 更多