Rotate List
Last updated
Last updated
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null) return null;
ListNode first = head;
ListNode second = head;
int size = 0;
while(first != null) {
size++;
first = first.next;
}
k %= size;
first = head;
int count = 1;
while (first != null && first.next != null) {
if (count > k) second = second.next;
first = first.next;
count++;
}
first.next = head;
ListNode result = second.next;
second.next = null;
return result;
}
}