Rotate List LeetCode Solution

Here, We see Rotate List LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Rotate List LeetCode Solution

Rotate List LeetCode Solution

Problem Statement

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

Example 1:

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

Example 2:

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

Rotate List Leetcode Solution C++

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (head == nullptr || head->next == nullptr) {
            return head;
        }
        auto iter = head;
        auto len = 1;
        while (iter->next != nullptr) {
            iter = iter->next; ++len;
        }
        iter->next = head;
        iter = head;
        for (int i = 0; i < len - (k % len) - 1; ++i) {
            iter = iter->next;
        }
        head = iter->next;
        iter->next = nullptr;
        return head;        
    }
};Code language: PHP (php)

Rotate List Leetcode Solution Java

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
    if (head==null||head.next==null) return head;
    ListNode dummy=new ListNode(0);
    dummy.next=head;
    ListNode fast=dummy,slow=dummy;
    int i;
    for (i=0;fast.next!=null;i++)
    	fast=fast.next;
    for (int j=i-k%i;j>0;j--)
    	slow=slow.next;
    fast.next=dummy.next;
    dummy.next=slow.next;
    slow.next=null;
    return dummy.next;        
    }
}Code language: PHP (php)

Rotate List Leetcode Solution JavaScript

var rotateRight = function(head, k) {
  if (!head || !head.next || !k) return head;
  const list = [];
  let len = 0;
  // put linked list into array
  for (let cur = head; cur; cur = cur.next) {
    list[len++] = cur;
  }
  // calculate the break position
  const newHead = len - (k % len);
  if (newHead === len) return head;
  // change pointer
  list[len - 1].next = head;
  list[newHead - 1].next = null;
  return list[newHead];    
};Code language: PHP (php)

Rotate List Leetcode Solution Python

class Solution(object):
    def rotateRight(self, head, k):
        n, pre, current = 0, None, head
        while current:
            pre, current = current, current.next
            n += 1
        if not n or not k % n:
            return head
        tail = head
        for _ in xrange(n - k % n - 1):
            tail = tail.next
        next, tail.next, pre.next = tail.next, None, head
        return next
Scroll to Top