Reverse a linked list from position m to N. Do it in-place and in one-pass.
For example:
Given1->2->3->4->5->NULL, M = 2 and N = 4,
Return1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
The idea is simple: set two pointers: fast move n steps forward, low move M steps forward, and then insert the nodes between low and fast one by one to the end of fast. Note: to remove the special characteristics of the header node, you need to use the virtual header node technology.
ListNode *reverseBetween(ListNode *head, int m, int n) { ListNode *dummyHead = new ListNode(0); dummyHead->next = head; ListNode *fast = head; for (int i = 0; i < n - 1; ++i) fast = fast->next; ListNode *low = dummyHead; for (int i = 0; i < m - 1; ++i) low = low ->next; for (int i = 0; i < n - m; ++i) { ListNode *curr = low->next; low ->next = low ->next->next; curr->next = fast->next; fast->next = curr; } head = dummyHead->next; delete dummyHead; return head;}
Leetcode [linked list]: reverse Linked List II