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.
For this type of question, two things should be paid attention to:
- If the first node is the head, take case of the predecessor of head.
- If the first node is the head, take case of the returning value.
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (m == n || head == NULL)
return head;
ListNode *p = head, *last = NULL, *next = NULL, *lastend = NULL;
int cur = 1;
while (p != NULL && cur <= n) {
next = p->next;
if (cur == m)
lastend = last;
if (cur >= m && cur <= n)
p->next = last;
last = p;
p = next;
++cur;
}
if (lastend == NULL) {
head->next = p;
return last;
}
else {
lastend->next->next = p;
lastend->next = last;
return head;
}
}
};