← All solutions
May 5Medium

Rotate list

  • Linked List
  • Two Pointers

Problem

Given the head of a linked list, rotate the list to the right by k places.

Solution

class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if not head:
            return head
        copy = head
        tail = head
        l = 0
        while copy:
            copy = copy.next
            l += 1
            if copy:
                tail = copy
        k = k % l
        if not k:
            return head
        end = head
        for i in range(l - k - 1):
            end = end.next 
        new_head = end.next
        end.next = None
        tail.next =  head
        return new_head