程式語言 - LeetCode - C++ - 92. Reverse Linked List II



題目:


解答:

/**
 * 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 d0;
        d0.next = head;
        ListNode *pre = &d0;

        for (int i = 0; i < left - 1; ++i) {
            pre = pre->next;
        }

        ListNode *cur = pre->next;
        for (int i = 0; i < right - left; ++i) {
            ListNode *t = cur->next;

            cur->next = t->next;
            t->next = pre->next;
            pre->next = t;
        }

        return d0.next;
    }
};