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

Machine Learning Projects

Table of Contents

Question

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

Example 1:

Machine Learning Projects
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

Example 2:

Machine Learning Projects
Input: head = [0,1,2], k = 4
Output: [2,0,1]

Constraints:

  • The number of nodes in the list is in the range [0, 500].
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 109

Python Solution

# 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: ListNode, k: int) -> ListNode:
        if head==None:
            return None
        if head.next==None:
            return head
        l = 0
        p1 = head
        
        while p1:
            p1 = p1.next
            l+=1
        
        k = k%l
        
        if k==0:
            return head
        
        slow = head
        fast = head
        
        for _ in range(k):
            fast = fast.next
        
        while fast.next:
            fast = fast.next
            slow = slow.next
        
        h = slow.next
        slow.next = None
        fast.next = head
        
        return h

Leave a Comment

Your email address will not be published.