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,m,n,n+1个元素,因此要记录这几个指针。
这里m有可能等于1,那么第m-1个元素就在链表之外,所以这里用一个dummy指针,省去繁琐的判断。
剩下的就是翻转链表的操作,基本是规范或者标准的做法了。声明3个指针ListNode *now,*last,*tmp。
now指向当前元素,last指向上一个元素,tmp用来缓存下一个元素的指针
tmp = now->next;
now->next = last;
last = now;
now = tmp;
下面就是代码:
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *Mminus1 = dummy, *M = head, *tmp, *now, *last;
for (int i = 1; i < m; i++){
Mminus1 = M;
M = M->next;
}
now = last = M;
for (int i = m; i <= n; i++){
tmp = now->next;
now->next = last;
last = now;
now = tmp;
}
Mminus1->next = last;
M->next = now;
return dummy->next;
}
};
一遍AC