反转从位置 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) {
if (m == n) return head;
auto dummy = new ListNode(-1);
dummy->next = head;
auto a = dummy, d = dummy;
while (--m) a = a->next;
while (n--) d = d->next;
auto b = a->next, c = d->next;
auto p = b, q = b->next;
while (q != c) {
auto o = q->next;
q->next = p;
p = q;
q = o;
}
a->next = d, b->next = c;
return dummy->next;
}
};