常规链表翻转的改版,注意记录翻转部分的头结点start及其前面的结点preStart、尾结点tail及其后面的结点postTail即可。在内部的结点翻转完毕(方法同常规链表翻转)后,将preStart->next = tail,start -> next = postTail,即可。代码如下:
/**
* 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 (head == NULL || m == n)
return head;
ListNode* preHead = new ListNode(0);
preHead -> next = head;
ListNode* p = preHead;
ListNode* q = head;
while (m > 1)
{
p = q;
q = q -> next;
--m;
--n;
}
ListNode* preStart = p;
ListNode* start = q;
p = q;
q = q -> next;
while (n > 1)
{
ListNode* r = q -> next;
q -> next = p;
p = q;
q = r;
--n;
}
preStart -> next = p;
start -> next = q;
return preHead -> next;
}
};