Problem:
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Analysis:
Solution:
C++:
ListNode *reverseBetween(ListNode *head, int m, int n) {
ListNode* start_back = head;
ListNode* start_front = head;
if(m > 1) {
start_front = start_back->next;
for(int start = 2; start < m; ++start) {
start_back = start_front;
start_front = start_back->next;
}
}
ListNode* end_back = start_front;
ListNode* end_front = end_back->next;
for(int end = m + 1; end <= n; ++end) {
ListNode* temp_next = end_front->next;
end_front->next = end_back;
end_back = end_front;
end_front = temp_next;
}
if(m == 1)
head = end_back;
else
start_back->next = end_back;
start_front->next = end_front;
return head;
}
Java:
Python: