题目:
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.
题意:
给定一个链表,翻转从第m个元素到第n个元素。
思路:
做这道题目需要比较细心,翻转后的那部分必须与它的前后部分连接起来。我们需要找到第一个需要翻转节点的前一个节点记作before_first,并且找到需要翻转的最后一个节点,那么翻转后before_first应该链接上这个节点。并且待翻转的第一个节点需要指向待翻转的最后一个节点的下一个节点。
以上。
代码如下:
/**
* 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 == NULL || head->next == NULL || m == 0 || n == 0 || m == n)return head;
ListNode* first = head, *second, *before_first = NULL, *res = head;
for (int i = 0; i < m - 1; i++) {
before_first = first;
first = first->next;
}
second = first->next;
for (int i = m; i < n - 1; i++)
second = second->next;
if (before_first != NULL)before_first->next = second;
else res = second;
ListNode* next;
before_first = first;
first = first->next;
before_first->next = second->next;
while (first != second) {
next = first->next;
first->next = before_first;
before_first = first;
first = next;
}
first->next = before_first;
return res;
}
};