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.
以前只会用swap的办法来整个reverse...同样的办法也可以用在这个上面但是不够简洁
插入法
1.链接当前于后一个的后一个
2. 把后一个插入到最前面 a) next->next=pre->next b)pre->next=next
3. 更新当前next, next=cur->next...画一画。。。我画了好久。。。我是不是太笨。。。tot
/**
* 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 dummy(0); // dummy head
dummy.next=head;
ListNode* pre=&dummy;
int i;
for (i=1; i<m; i++)
pre=pre->next;
ListNode* cur=pre->next;
ListNode* next=cur->next;
for(i=0; i<n-m; i++){
cur->next=next->next;
next->next=pre->next;
pre->next=next;
next=cur->next;
}
return dummy.next;
}
};