首页 > 解决方案 > 用 2 个指针反转链表

问题描述

我正在尝试仅使用两个指针创建一个链接列表(我查看的每个帖子似乎都使用 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

标签: c++pointerslinked-list

解决方案


让它更简单,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
    }
}

推荐阅读