Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if(head==null)return null;
if(n==0)return head;
ListNode beginNode=head;
ListNode curNode=head;
ListNode returnNode;
int t=0;
for(int i=0;i<n;i++)
{
curNode=curNode.next;
if(curNode==null)
{
if(i==n-1||i==0||n%(i+1)==0)return head;
t=n%(i+1);
curNode=head;
for(int j=0;j<t;j++)
{
curNode=curNode.next;
}
break;
}
}
while(curNode.next!=null)
{
beginNode=beginNode.next;
curNode=curNode.next;
}
//curNode=beginNode.next;
returnNode=beginNode.next;
beginNode.next=null;
curNode.next=head;
return returnNode;
}
}