Skip to content
On this page

61. Rotate List

https://leetcode.com/problems/rotate-list/

js
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var rotateRight = function(head, k) {
    if (!head || !k) {
        return head
    }

    var current = head
    var size = 1

    while (current.next) {
        current = current.next
        size++
    }

    if (!(k = k % size)) {
        return head
    }

    var fast = head
    var slow = head

    for (let i = 0; i < k; i++) {
        fast = fast.next
    }

    while (fast.next) {
        fast = fast.next
        slow = slow.next
    }

    fast.next = head
    head = slow.next
    slow.next = null

    return head
}
py
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution(object):

    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or not k:
            return head

        current, size = head, 1
        while current.next:
            current = current.next
            size += 1
        k = k % size
        if not k:
            return head

        fast = slow = head
        for i in range(k):
            fast = fast.next
        while fast.next:
            fast = fast.next
            slow = slow.next

        fast.next = head
        head = slow.next
        slow.next = None

        return head