需要虚拟个头结点dummy,整个链表分为三个部分,如下图步骤所示:
class Solution {
public:
ListNode* reverseList(ListNode* head, int SubLength,ListNode*& pThirdHead) {
ListNode* pre = NULL;
ListNode* cur = head;
ListNode* next = NULL;
while(cur != NULL && SubLength--){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
pThirdHead = cur;
return pre;
}
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(m == n) return head;
ListNode* Dummy= new ListNode(0);
Dummy ->next = head;
int SubLength = n - m + 1;
ListNode* pFirstTail = PreHead;//左边部分的尾节点
ListNode* pSecondTail = NULL; //中间部分的头结点、反转后的尾节点
ListNode* pThirdHead = NULL; //右边部分右边的头结点
int k = m - 1;
while(k-- > 0){
pFirstTail = pFirstTail->next;
}
pSecondTail = pFirstTail->next;
pFirstTail->next = reverseList(pSecondTail, SubLength, pThirdHead);
pSecondTail->next = pThirdHead;
return Dummy ->next;
}
};