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
.
Subscribe to see which companies asked this question
不难,注意k超过链表长度之后就要取余
/**
* 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) {
if(k==0||head==null)return head;
ListNode fast = head;
int length = 1;
int flag = 0;
for(int i = 0;i<k;i++){
if(fast.next!=null)length++;
else{flag=1; break;}
fast = fast.next;
}
if(flag==1){
k=k%length;
if(k==0)return head;
fast=head;
for(int i = 0;i<k;i++){
fast=fast.next;
}
}
ListNode slow = head;
while(fast.next!=null){
fast=fast.next;
slow=slow.next;
}
ListNode ret = slow.next;
slow.next=null;
fast.next=head;
return ret;
}
}