給你一個鏈表,每 k 個節點一組進行翻轉,請你返回翻轉後的鏈表。javascript
k 是一個正整數,它的值小於或等於鏈表的長度。java
若是節點總數不是 k 的整數倍,那麼請將最後剩餘的節點保持原有順序。git
示例 :github
給定這個鏈表:1->2->3->4->5oop
當 k = 2 時,應當返回: 2->1->4->3->5spa
當 k = 3 時,應當返回: 3->2->1->4->5code
var reverseList = function(head) {
let pre = null
let curr = head
let next;
while (curr != null) {
next = curr.next
curr.next = pre;
pre = curr;
curr = next;
}
return pre
};
var reverseKGroup = function(head, k) {
let revList = new ListNode(0)
revList.next = head
let pre = revList
let end = revList
let loopCurr = head
while (end != null) {
for(let i = 0; i < k && end != null; i ++ ) {
end = end.next
}
if (end == null) break;
let start = pre.next
let next = end.next
end.next = null;
pre.next = reverseList(start);
start.next = next;
pre = start;
end = pre;
}
return revList.next
};
複製代碼
題解回頭補上,太晚了,先休息了。
源碼ip