Reverse Linked List II
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-m
每次交换时,把下一个元素交换到需要交换的初始位置
如
1->2->3->4->5->NULL
找到交换位置
1->
->3->4->5->NULL
把下一个元素交换到需要交换的初始位置
1->
->
2
->4->5->NULL
继续交换
1->
->
3
->
2
->5->NULL
注意初始位置在开头时,每次交换都要更新head
/**
* 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) { ListNode *p1=head;
ListNode *p1Pre=new ListNode(); int k=n-m; p1Pre->next=p1; ListNode *needDelete=p1Pre; while(m->)
{
p1Pre=p1;
p1=p1->next;
m--;
} while(k>)
{
ListNode* cur=p1->next;
p1->next=cur->next; if(p1Pre->next==head)
{
head=cur;
} cur->next=p1Pre->next;
p1Pre->next=cur; k--;
} delete needDelete;
return head;
}
};