Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

K 个一组翻转链表 #293

Open
Sunny-117 opened this issue Nov 8, 2022 · 1 comment
Open

K 个一组翻转链表 #293

Sunny-117 opened this issue Nov 8, 2022 · 1 comment

Comments

@Sunny-117
Copy link
Owner

No description provided.

@Nasuke
Copy link
Contributor

Nasuke commented Nov 20, 2022

// 反转链表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
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants