Rotate Linked List

Rotate a linked list to the right by k places

Read Here
Step0 / 12
PhaseInitialize
Nodes5
K2
Back To Linked List

Code

1def rotateRight(head, k):
2 if not head or not head.next or k == 0:
3 return head
4
5 # Find length and tail
6 length = 1
7 tail = head
8 while tail.next:
9 length += 1
10 tail = tail.next
11
12 # Compute effective rotations
13 k = k % length
14 if k == 0:
15 return head
16
17 # Find new tail (length - k - 1 steps)
18 new_tail = head
19 for _ in range(length - k - 1):
20 new_tail = new_tail.next
21
22 new_head = new_tail.next
23 new_tail.next = None
24 tail.next = head
25 return new_head
Function definition

Linked List

INIT

Step

0 / 12

Phase

Initialize

Nodes

5

K

2

null1next2next3next4next5next

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.