Title Description
Reversed from the position m to n list. Use single pass complete reversal.
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
Reference Code
General questions, "many hands" do not like chain scission. (With a total of 2 + 5 3 == pointer)
/**
* 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 == nullptr)
return nullptr;
ListNode* dummyHead = new ListNode(-1); // 很好用!
dummyHead->next = head;
ListNode* pFront = dummyHead;
ListNode* pNode = head;
for(int i = 0; i < m-1; i++){
pFront = pNode;
if(pNode != nullptr)
pNode = pNode->next;
}
ListNode* pPre = nullptr;
int cnt = n - m + 1;
while(pNode && cnt--){
ListNode* pNext = pNode->next;
pNode->next = pPre;
pPre = pNode;
pNode = pNext;
if(cnt == 0){
pFront->next->next = pNode;
pFront->next = pPre;
}
}
return dummyHead->next;
}
};