问题描述:
Reverse a linked list from position m to n. Do it in-place and in one-pass.
示例:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
问题分析:
将m到n间的结点顺序反转,然后将1到m-1 、 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 == NULL || m == n) return head;
ListNode res(0);
res.next = head;
int i = 1;
int flag = 0;
ListNode * last = &res, *newTail, *temp, *newTailbre;
while (head)
{
if (i == m)
{
flag = 1;
newTail = head;
newTailbre = last;
}
else if (i == n)flag = 2;
if (flag == 1)
{
temp = head->next;
head->next = last;
}
else if (flag == 2)
{
temp = head->next;
head->next = last;
newTailbre->next = head;
newTail->next = temp;
break;
}
last = head;
if (!flag)
head = head->next;
else head = temp;
i++;
}
return res.next;
}
};