题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
分组翻转,在每一组内用front, mid, back三个指针,每次调整mid指向的节点 /*class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ export function reverseKGroup(head: ListNode, k: number): ListNode { // write code here let total = 0; let p: ListNode | null = head; // 先统计总共有多少个节点 while (p) { p = p.next; total++; } let times = Math.floor(total / k); // 有多少组k if (times < 1) { // 节点数都不够一组k的,直接返回 return head; } let front = null; // 前指针 let mid: ListNode | null = head; // 中间指针,指向当前要反转的节点 let back = null; // 后指针 let groupCount = 1; // 统计反转到第几组了 let newHead: ListNode | null = null; // 全部调整完后新链表的头 let preGroupTail: ListNode | null = null; // 指向前一组调整完后的尾节点,因为它要连接下一组的头节点 while (groupCount <= times) { let count = 1; // 每组内的计数 let tail = mid; while (count <= k && mid) { back = mid.next; mid.next = front; front = mid; mid = back; count++; } if (groupCount === 1) { // 调整完后的新链表的头指针 newHead = front; } else { (preGroupTail as ListNode).next = front; } front = null; preGroupTail = tail; groupCount++; } (preGroupTail as ListNode).next = mid; return newHead as ListNode; }