题目:
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.
思路:
第一步是利用指针定位需要旋转的指针头;第二步是针对指定长度的指针旋转;第三部是将剩下的指针赋予尾部。
代码:
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode* p = new ListNode(0);
p->next = head;
ListNode* begin = p;
int tmp = m - 1;
while(tmp > 0)
{
p = p->next;
tmp--;
};
ListNode * cur = p->next;
p->next = NULL;
tmp = n - m + 1;
while(tmp-- > 0)
{
ListNode * t = cur->next;
cur->next = p->next;
p->next = cur;
cur = t;
};
while(p->next != NULL)
{
p = p->next;
};
if(cur != NULL)
{
p->next = cur;
};
begin = begin->next;
return begin;
}
};