Rotate List Leetcode Solution

In this post, we are going to solve the Rotate List Leetcode Solution problem of Leetcode. This Leetcode problem is done in many programming languages like C++, Java, and Python.

Rotate List Leetcode Solution
Rotate List Leetcode Solution

Problem

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

Example 1:Rotate List Leetcode Solution

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

Example 2:Rotate List Leetcode Solution

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

Now, lets see the leetcode solution of Rotate List Leetcode Solution.

Rotate List Leetcode Solution in Python

class Solution:
  def rotateRight(self, head: ListNode, k: int) -> ListNode:
    if not head or not head.next or k == 0:
      return head

    tail = head
    length = 1
    while tail.next:
      tail = tail.next
      length += 1
    tail.next = head  # Circle the list

    t = length - k % length
    for _ in range(t):
      tail = tail.next
    newHead = tail.next
    tail.next = None

    return newHead

Rotate List Leetcode Solution in CPP

class Solution {
 public:
  ListNode* rotateRight(ListNode* head, int k) {
    if (!head || !head->next || k == 0)
      return head;

    ListNode* tail;
    int length = 1;
    for (tail = head; tail->next; tail = tail->next)
      ++length;
    tail->next = head;  // Circle the list

    const int t = length - k % length;
    for (int i = 0; i < t; ++i)
      tail = tail->next;
    ListNode* newHead = tail->next;
    tail->next = nullptr;

    return newHead;
  }
};

Rotate List Leetcode Solution in Java

class Solution {
  public ListNode rotateRight(ListNode head, int k) {
    if (head == null || head.next == null || k == 0)
      return head;

    int length = 1;
    ListNode tail = head;
    for (; tail.next != null; tail = tail.next)
      ++length;
    tail.next = head; // Circle the list

    final int t = length - k % length;
    for (int i = 0; i < t; ++i)
      tail = tail.next;
    ListNode newHead = tail.next;
    tail.next = null;

    return newHead;
  }
}

Note: This problem Rotate List is generated by Leetcode but the solution is provided by Chase2learn This tutorial is only for Educational and Learning purposes.

NOTE: Unique Paths Leetcode Solution

Sharing Is Caring