Given a list, rotate the list to the right bykplaces, wherekis non-negative.
Given 1->2->3->4->5->NULL and k= 2,
return 4->5->1->2->3->NULL.
/**
* 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 || k == 0) {
return head;
}
int len = 1;
ListNode curNode = head;
while (curNode.next != null) {
curNode = curNode.next;
++len;
}
k %= len;
curNode.next = head;
for (int i = 0; i < len - k; i++) {
curNode = curNode.next;
}
head = curNode.next;
curNode.next = null;
return head;
}
}
3. Time & Space Complexity