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