题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/*
* 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 || !head.next || k === 1) {
return head;
}
let cur = head;
let i = 0;
let group = [];
let curList;
let count = 0;
while (cur) {
cur = cur.next;
count++;
}
if (count < k) {
return head;
}
cur = head;
while (cur) {
let temp = cur;
cur = cur.next;
if (i % k === 0) {
if (i > 0) {
group.push(curList);
}
if (k * (group.length + 1) > count) {
group.push(temp);
break;
} else {
curList = temp;
curList.next = null;
}
} else {
temp.next = curList;
curList = temp;
}
i++;
}
if (count === k) {
return curList;
}
head = group[0];
for (let j = 0; j < group.length; j++) {
let next = group[j];
while (next) {
if (!next.next) {
next.next = group[j + 1];
next = null;
} else {
next = next.next;
}
}
}
return head;
}
module.exports = {
reverseKGroup: reverseKGroup,
};
解题思路:按组分别翻转,然后重新连接
#链表翻转#