/**
* 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 || head.next == null || k == 0){
return head;
}
ListNode root = new ListNode(-1);
int count = 0;
for(ListNode node = head; node != null;node = node.next){
count += 1;
if(node.next == null){ //end
node.next = head;
break;
}
}
k = k%count;
k = count - k;
count = 0;
for(ListNode node = head; node != null;node = node.next){
count += 1;
if(k == count){
root.next = node.next;
node.next = null;
break;
}
}
return root.next;
}
}
网友评论