Ray-56 / like-algorithms

每天一道算法题,突破自己
2 stars 1 forks source link

✅25. K 个一组翻转链表 #159

Open Ray-56 opened 4 years ago

Ray-56 commented 4 years ago

25. K 个一组翻转链表

给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

示例:

给你这个链表:1->2->3->4->5

当 k = 2 时,应当返回: 2->1->4->3->5

当 k = 3 时,应当返回: 3->2->1->4->5

说明:

Ray-56 commented 4 years ago

到每个 K 的位置,保存头尾,然后将头尾进行翻转,返回

/**
 * 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) {
    const hair = new ListNode(0);
    hair.next = head;
    let pre = hair;

    while (head) {
        let tail = pre;
        // 检查剩余长度
        for (let i = 0; i < k; i++) {
            tail = tail.next;
            if (!tail) return hair.next;
        }
        const next = tail.next;
        [head, tail] = reverseList(head, tail);
        // 把子链表重新接回原链表
        pre.next = head;
        tail.next = next;
        pre = tail;
        head = tail.next;
    }
    return hair.next;
};

function reverseList(head, tail) {
    let pre = tail.next;
    let cur = head;

    while (pre !== tail) {
        const next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    return [tail, head];
}