题目
解题思路
直接实现反转K个一组翻转链表可能非常困难,但是可以分成长度为K的子串,每一个字串分别反转并拼接,最后返回即可。
反转链表
反转链表很容易实现,可以通过递归/迭代的形式实现。
这里采用的是判断 递归 + 是否为null为basecase 实现
function reverse(head: ListNode | null): ListNode | null {
if (head === null || head.next === null) return head;
const prev = reverse(head.next);
head.next.next = head;
head.next = null;
return prev;
}
反转K个
分析可以发现,整体的过程就可以分解成长度为 K
的部分字串,所以明显可以使用递归来实现。
- 遍历当前的链表,如果长度不足
k
,则直接返回头节点,这里需要注意的是if
判断条件需要放在p.next前还是后的问题 - 保留后驱节点以及设置满足反转的basecase,即记录
successor
和设置p.next = null
- 反转当前长度为
k
的字串,得到新的头节点 - 拼接
当前的最新尾节点
和下一个
最新的头节点
- 返回最新的头节点
代码
/**
* Definition for singly-linked list.
* 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)
* }
* }
*/
// 理解题意:每隔K个就反转当前的短链表,不足K个则不反转
// 从理解提议中可以看出,每个K个就反转,不足K个不反转,可以使用子问题的方式,也就是可以使用递归
function reverseKGroup(head: ListNode | null, k: number): ListNode | null {
if (head === null) return head;
let p = head;
for (let i = 1; i < k; i++) { // 从1开始算
p = p.next; // 进行迭代
if (p === null) return head; // 如果不足k个,直接返回当前的头节点,注意放在前面和放在后面的不同
}
// 以下的过程表示需要反转当前的部分链表
let successor = p.next; // 保留后驱节点
p.next = null; // 为了形成basecase,切断next指针,使其指向null
const newHead = reverse(head); // 开始反转得到新头节点
head.next = reverseKGroup(successor, k); // 最新的尾节点拼接下一个最新的头节点
return newHead;
}
function reverse(head: ListNode | null): ListNode | null {
if (head === null || head.next === null) return head;
const prev = reverse(head.next);
head.next.next = head;
head.next = null;
return prev;
}