【路飞】leetcode 61 旋转链表

287 阅读1分钟

思路:遍历链表,计算出链表的长度,同时将链表最后一个节点和头节点相连,形成一个环形链表。然后计算出链表实际需要移动次数,开始移动链表,最后断开链表并返回

var rotateRight = function(head, k) {
    if (!k || !head || !head.next) {
        return head
    }
    let n = 1
    let cur = head
    while(cur.next) {
        cur = cur.next
        n++
    }
    let add = n - k % n
    if (add === n) return head
    cur.next = head
    while (add) {
        cur = cur.next
        add--
    }
    let res = cur.next
    cur.next = null
    return res
};