92. 反转链表 II
https://leetcode-cn.com/problems/reverse-linked-list-ii/description/
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* Head = new ListNode(-1);
Head->next = head;
ListNode* cur1 = Head;
ListNode* cur2;
ListNode* prev = NULL;
ListNode* next;
int k = n - m;
for (int i = 0; i < m - 1; ++i) {
cur1 = head;
head = head->next;
}
cur2 = head;
for(int i = 0; i <= k; ++i) {
next = head->next;
head->next = prev;
prev = head;
head = next;
}
cur1->next = prev;
cur2->next = head;
return Head->next;
}
};