Rotate List - LeetCode Solution in Java and C++
Hello Friends, How are you? Today I am going to solve the Rotate List LeetCode Problem with a very easy explanation. In this article, you will get solutions in more than one language to solve this problem. So let's start-
{tocify} $title={Table of Contents}
LeetCode Rotate List 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] {codeBox}
Example 2:
Input: head = [0,1,2], k = 4 Output: [2,0,1] {codeBox}
Constraints:
- The number of nodes in the list is in the range [0, 500].
- -100 <= Node.val <= 100
- 0 <= k <= 2 * 109
Rotate List - LeetCode Solution
Rotate List LeetCode Solution in Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null || head.next == null || k == 0) {
return head;
}
ListNode temp = head;
int len = 1;
while(temp.next != null) {
len++;
temp = temp.next;
}
temp.next = head;
k = k % len;
k = len - k;
while(k != 0) {
temp = temp.next;
k--;
}
head = temp.next;
temp.next = null;
return head;
}
}
Rotate List LeetCode Solution in C++
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head) return head;
int len=1; // number of nodes
ListNode *newH, *tail;
newH=tail=head;
while(tail->next) // get the number of nodes in the list
{
tail = tail->next;
len++;
}
tail->next = head; // circle the link
if(k %= len)
{
for(auto i=0; i<len-k; i++) tail = tail->next; // the tail node is the (len-k)-th node (1st node is head)
}
newH = tail->next;
tail->next = NULL;
return newH;
}
}
Disclaimer: The above Problem ( Rotate List Problem ) is generated by LeetCode but the Solution is Provided by MyEduWaves. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the contact form.
I hope you have understood the solution to this LeetCode Problem. All these solutions will pass all the test cases. Now visit Rotate List LeetCode Problem and try to solve it again.
All the Best!