题目:
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.
思路:
这道题目的思路不难,需要注意的是in-place和one-pass的要求。假设需要翻转m到n之间的元素,那么我们首先定位到m位置,然后遍历并且依次翻转,直到到达n位置。最后把m位置的元素和n之后的元素连接起来即可。为了处理方便,仍然引入虚拟头结点。
代码:
/**
* 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 || n - m <= 0) {
return head;
}
ListNode pre_head(0);
pre_head.next = head;
ListNode* p = &pre_head;
ListNode* post;
int i = 1;
while(i < m && p) { // come to position m
p = p->next;
i++;
}
post = p->next;
ListNode* q = post->next;
while(q && i < n) { // traverse until position n
ListNode* temp = q->next;
q->next = p->next;
p->next = q;
q = temp;
i++;
}
post->next = q;
return pre_head.next;
}
};