- categories: Code, Interview Question, leetcode, Medium
- source: https://leetcode.com/problems/rotate-list
- topics: Linked List
Given the head
of a linked list, rotate the list to the right by k
places.
Idea
Find the length and last element, break the list at len-k
and unite tail with head
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head or k == 0:
return head
list_len = 1
cur = head
while cur.next:
list_len += 1
cur = cur.next
k = k % list_len
last = cur
if k == 0:
return head
cur = head
for _ in range(list_len - k - 1):
cur = cur.next
last.next = head
head = cur.next
cur.next = None
return head