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) {
ListNode * dummy = new ListNode(0);
dummy->next = head;
ListNode * pre = dummy;
int i = m;
while(--i > 0 && pre != NULL){
pre = pre->next;
}
ListNode * mpre = pre;
if(!mpre)
return head;
ListNode * pM = mpre->next;
i = n - m;
if(i > 0){
pre = pM;
if(!pre)
return head;
ListNode * pTemp = pre->next;
ListNode * pNext = NULL;
while(i-- > 0 && pTemp){
pNext = pTemp->next;
pTemp->next = pre;
pre = pTemp;
pTemp = pNext;
}
mpre->next = pre;
pM->next = pTemp;
}
return dummy->next;
}
};
自己第一次写的时候把没有保存m和n,直接先对m作–m操作,再对n作n-=m的操作,结果导致自己被坑了一个晚上,以后写代码一定要注意尽量对参数进行保存。
/**
* 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);
if(!head)
return head;
dummy.next = head;
ListNode * pre = &dummy;
for(int i = 1; i < m; i++){
pre = pre->next;
}
ListNode * mpre = pre;
ListNode * pm = mpre->next;
pre = pm;
ListNode * cur = pm->next;
for(int i = m; i < n; i++){
ListNode * temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
mpre->next = pre;
pm->next = cur;
return dummy.next;
}
};
经过提醒出一个简洁版本。
/**
* 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);
if(!head)
return head;
dummy.next = head;
ListNode * pre = &dummy;
for(int i = 1; i < m; i++){
pre = pre->next;
}
ListNode * pm = pre->next;
for(int i = m; i < n; i++){
ListNode * pn = pm->next;
pm->next = pn->next;
pn->next = pre->next;//注意不能使用pn->next=pm,因为即将修改pre->next
pre->next = pn;
}
return dummy.next;
}
};