跳转至

反转链表 II⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

注:在反转链表后,从原来的链表上看,pre指向反转这一段的末尾,curr指向反转这一段后续的下一个节点。

/**
 * 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* reverseBetween(ListNode* head, int left, int right) {
        ListNode* dummy = new ListNode(0, head);

        ListNode* before = dummy;
        for (int i = 0; i < left - 1; i++) {
            before = before->next;
        }

        ListNode* pre = nullptr;
        ListNode* curr = before->next;
        for (int i = 0; i < right - left + 1; i++) {
            ListNode* originalNext = curr->next;
            curr->next = pre;
            pre = curr;
            curr = originalNext;
        }

        before->next->next = curr;
        before->next = pre;

        return dummy->next;
    }
};