【leetcode】61. 旋转链表

67 阅读1分钟

leetcode-61.png

跟旋转数组一样的意思,这里要处理好k的值过大的问题,也就是一个除余可以解决的问题。
这里利用快慢指针,找到需要断开的地方即可,然后还有一个需要注意的地方,断开地方的后半部分要衔接到链表头部,断开的前半部分的尾部,需要置空,不然就会形成环形

var rotateRight = function (head, k) {
    if (!head || !head.next || k === 0) {
        // 链表为空、只有一个节点,或旋转步数为0时,直接返回原链表
        return head;
    }
    let n = 0
    let tail = head
    while (tail) {
        tail = tail.next
        n++
    }
    k %= n
    if (k === 0) return head
    let slow = head, fast = head
    while (k--) {
        fast = fast.next
    }
    while (fast.next) {
        slow = slow.next
        fast = fast.next
    }
    // 断开部分的后面,衔接到头部
    fast.next = head
    // 存放新链表的头部
    let newHead = slow.next
    // 链表尾部置空
    slow.next = null
    return newHead
};

下面的思路一样

var rotateRight = function (head, k) {
    if(!head || !head.next) return head
    if(k === 0) return head
    let length = 0;
    let current = head;
    while (current) {
        current = current.next;
        length++;
    }
    let rest = k % length;
    if(rest === 0) return head
    let slow = head,
        fast = head;
    while (rest--) {
        fast = fast.next;
    }
    while (fast.next) {
        fast = fast.next;
        slow = slow.next;
    }
    let start = slow.next;
    fast.next = head;
    slow.next = null;
    return start;
};