Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL题源: here;完整实现: here
思路:
我们在遍历的过程中,当遇到转移范围内的数就将其存放在另一个反置的链表中,当结束时就插入原链表。代码如下:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode feakHead = ListNode(0); feakHead.next = head;
head = &feakHead;
ListNode *curr = head;
ListNode *currB = NULL;
ListNode *startR = NULL;
ListNode *endR = NULL;
while (curr->next){
m--; n--;
if (m <= 0){
if (!currB) currB = curr;
if (!startR) startR = new ListNode(curr->next->val);
if (!endR) endR = startR;
else{
ListNode *temp = new ListNode(curr->next->val);
temp->next = startR;
startR = temp;
}
}
if (n <= 0) break;
curr = curr->next;
}
endR->next = curr->next->next;
currB->next = startR;
return head->next;
}
纪念贴图: