Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

K 个一组翻转链表

Sunny-117 opened this issue · comments

commented
// 反转链表n个结点的方法
var __reverseN = function(head, n) {
    if (n == 1) return head
    let tail = head.next, p = __reverseN(head.next, n - 1)
    head.next = tail.next
    tail.next = head
    return p
}
// 判断是否需要进行反转,如果剩余结点个数小于n,直接返回head
var reverseN = function(head, n) {
    let cut = n, p = head
    while(--n && p) p = p.next
    if (!p) return head
    return __reverseN(head, cut)
}
// 定义一个虚头ret指向head,p指针指向ret),q指针指向p.next(头节点翻转后变尾节点)
// 令p.next指向反转后的结点,如果和q相等,则证明反转结束,返回ret.next
// 如果p.next和q不相等,则证明反转结点成功,准备进行下一轮反转,让p指向q,q指向q.next
var reverseKGroup = function(head, k) {
    let ret = new ListNode(null, head), p = ret, q = p.next
    while((p.next = reverseN(q, k)) != q) {
        p = q
        q = q.next
    }
    return ret.next
};