//反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 
//
// 说明: 
//1 ≤ m ≤ n ≤ 链表长度。 
//
// 示例: 
//
// 输入: 1->2->3->4->5->NULL, m = 2, n = 4
//输出: 1->4->3->2->5->NULL 
// Related Topics 链表 
// 👍 683 👎 0

/*
* 92 反转链表 II
* 2021-02-26 22:55:34
* @author oxygenbytes
*/ 
#include "leetcode.h" 
//leetcode submit region begin(Prohibit modification and deletion)
/**
 * 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) {
        if(left == right) return head;

        ListNode dummy(-1);
        auto ptr = &dummy;
        ptr->next = head;

        auto a = ptr, c = ptr;
        for(int i = 0;i < left - 1;i++) a = a->next;
        for(int i = 0;i < right;i++) c = c->next;

        auto b = a->next, d = c->next;
        // result a->b .... c->d

        // reverse list from b ... c
        for(auto p = b, q = b->next; q != d;){
            auto temp = q->next;
            q->next = p;
            p = q, q = temp;
        }

        b->next = d;
        a->next = c;
        return dummy.next;
    }
};
//leetcode submit region end(Prohibit modification and deletion)