Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
开始没考虑k比链表长度大的情况,其实到现在我们不清楚为啥要考虑这种情况,难道是为了增加难度?
当k大于链表长度n时,相当于k=k%n;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k)
{
ListNode p1=head,p2=head;
if(k==0||head==null)
return head;
for(int i=0;i<k;i++)
{
p1=p1.next;
if(p1==null)
{
k=k%(i+1);
if(k!=0)
{
i=-1;
p1=head;
}
else
return head;
}
}
while(p1.next!=null)
{
p1=p1.next;
p2=p2.next;
}
ListNode newHead=p2.next;
p2.next=null;
p1.next=head;
return newHead;
}
}