Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Rotate a Singly Linked List in Python

Rotate a linked list left or right, handle negative and oversized shifts, and compare an in-place solution with a copied list.

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.

Shift linked list problem Picture 1

Rotate the existing nodes in place

Shift linked list problem Picture 2
Join the old tail to the old head, then cut the link at the new tail.

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

Shift linked list problem Picture 3
A Python list makes the cut point easier to visualize.

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.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.