思路: 每次进行翻转的时候,先判断当前结点直到末尾够不够K个节点,不够的话直接返回。 一次循环后,我们可以得到翻转后链表的头节点(head),尾节点(tail)以及下次翻转开始的节点(next)。 此方法时间复杂度是: O(N),空间复杂度:O(1)
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
function reverseKGroup( head , k ) {
// write code here
if(!head || k === 1) return head;
let temp = head;
const res = {val: -1, next: null};
let tail = res;
while(temp) {
const res = reverse(temp, k);
tail.next = res.head;
tail = res.tail;
temp = res.next;
}
return res.next;
}
/**
* 辅助函数
*/
function reverse(head, k){
let tail = head;
for(let i = 0;i < k - 1;i++){
if(!tail.next) return {head, tail, next: null};
tail = tail.next;
}
let pre = null, cur = head, next = null;
for(let i = 0;i < k;i++){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return {head: pre, tail: head, next};
}
module.exports = {
reverseKGroup : reverseKGroup
};