/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var reverseKGroup = function (head, k) {
if (k === 1 || k === 0 || head === null || head.next === null) {
return head;
}
// 定义一个保护节点
let protect = new ListNode(0, null);
let last = protect;
let nextGroupStart = null;
// 反转一串链表,前一个链表的结尾 + 反转本身 + 后一个链表的开始
while (head !== null) {
// 获取最后一个节点,用于反转
let end = getEnd(head, k);
// 如果到了最后不够了,保持原有顺序,直接返回即可
if (end === null) {
break;
}
// 记录后一个链表的开始
nextGroupStart = end.next;
// 反转本身,head到end反转
let reversed = reverseList(head, end);
// 子链表的开头(现在的end)和上一个链表结尾结合
last.next = reversed;
// 子链表的结尾(现在的head)和下一个链表开始结合
head.next = nextGroupStart;
// 当前结尾下一个循环时已成上一个链表的结尾(现在的head)
last = head;
// 让下一个子链表开始处理吧
head = nextGroupStart;
}
return protect.next;
}
// 找到最后一个节点,返回null说明最后已经不够k个了
const getEnd = function (head, k) {
let index = 1;
while (head !== null) {
head = head.next;
if (++index === k) {
return head;
}
}
return null; // or head, depending on how you want to handle it
}
// 反转head-end之间的链表
const reverseList = function (head, end) {
if (head === null || head.next === null) {
return head;
}
let next = head.next;
head.next = null;
let p;
let current = head;
let nextNode = next;
while (nextNode !== null && current !== end) {
p = nextNode.next;
nextNode.next = current;
current = nextNode;
nextNode = p;
}
return current; // could return 'head' if you want to maintain the original 'head' pointer, but it's not necessary since we know the new head will be the current node at this point anyway. (returns head if head === end or head === null)
}