Rotate Linked List
Rotate a linked list to the right by k places
Code
1def rotateRight(head, k):2 if not head or not head.next or k == 0:3 return head45 # Find length and tail6 length = 17 tail = head8 while tail.next:9 length += 110 tail = tail.next1112 # Compute effective rotations13 k = k % length14 if k == 0:15 return head1617 # Find new tail (length - k - 1 steps)18 new_tail = head19 for _ in range(length - k - 1):20 new_tail = new_tail.next2122 new_head = new_tail.next23 new_tail.next = None24 tail.next = head25 return new_head
Function definition
Linked List
INIT
Step
0 / 12
Phase
Initialize
Nodes
5
K
2
Progress
Processing
Rotating linked list to the right by k places...
Pointer State
Pointers
head
0
tail
null
curr
null
newTail
null
Key Insight
Connect tail to head, then break the link at (length - k - 1) to form the rotated list.
Explanation
INIT
Initialize
Rotate list [1, 2, 3, 4, 5] right by 2 places.
💡 Tip
Edge case: if list has 0 or 1 nodes, or k == 0, return as-is.