Table of Contents
Rotating a singly linked list moves a group of nodes from one end to the other without changing their order inside the group. Here, a positive k rotates right and a negative k rotates left. For 0 → 1 → 2 → 3 → 4 → 5, a shift of 2 gives 4 → 5 → 0 → 1 → 2 → 3. A shift of −2 gives 2 → 3 → 4 → 5 → 0 → 1.

Rotate the existing nodes in place

Count the nodes and find the old tail. In Python, k % length gives the equivalent right shift even when k is negative. A zero result leaves the list unchanged. For a nonzero right shift, the new tail sits at zero-based index length - right - 1.
def rotate_linked_list(head, k):
if head is None:
return None
length = 1
old_tail = head
while old_tail.next is not None:
old_tail = old_tail.next
length += 1
right = k % length
if right == 0:
return head
new_tail = head
for _ in range(length - right - 1):
new_tail = new_tail.next
new_head = new_tail.next
new_tail.next = None
old_tail.next = head
return new_head
This version finds the cut before changing any links, then detaches the suffix and connects its tail to the old head. It takes O(n) time and O(1) extra space. The caller must keep the returned head. The function assumes the input has no cycle.
Build a rotated copy from a Python list

If the original links must stay in place, read the values into a Python list. Return an empty result for an empty input. Otherwise calculate right = k % len(values), set cut = len(values) - right, and rebuild new nodes from values[cut:] + values[:cut]. The copy takes O(n) time and O(n) extra space.
Test an empty list, one node, zero, a multiple of the length, and both shift directions. Rotation changes the starting node and wraps the end around. Reversing a linked list changes the direction of every link.
Reader Comments 0
Sign in with email or Google to join the discussion.