Skip to main content

Rotate List

Question

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1
Input: 1->2->3->4->5->NULL
K = 2

Output: 4->5->1->2->3->NULL

Solution

all//Rotate List.py


# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next


class Solution:
def rotateRight(self, head, k):
if not head:
return head

length = 0
node = head
while node:
length += 1
node = node.next

k = k % length
if k == 0:
return head

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

while fast.next:
fast = fast.next
slow = slow.next

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

return newHead