61. Rotate List
Given a list, rotate the list to the right bykplaces, wherekis non-negative.
For example:
Given1->2->3->4->5->NULLandk=2,
return4->5->1->2->3->NULL.
思路:先计算长度,取模得到移动步长。然后用双指针
public ListNode rotateRight(ListNode head, int k) {
if (head==null||head.next==null){
return head;
}
ListNode slow = head;
ListNode fast = head;
//get length
int i = 1;
while(fast.next!=null){
fast = fast.next;
i++;
}
//move slow
int slowstep = (i-k%i);
if (slowstep == i){
return head;
}
ListNode slowPrev = null;
for (int j=0;j<slowstep;j++){
slowPrev = slow;
slow = slow.next;
}
//reorgnize
fast.next = head;
slowPrev.next = null;
return slow;
}
GE:
/**
* 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(head==null ||head.next==null){
return head;
}
ListNode slow = head;
ListNode fast = head;
int len = 0;
while(fast!=null){
len++;
fast=fast.next;
}
fast = head;
for(int i= 0; i<k%len; i++){
fast = fast.next;
}
while(fast.next!=null){
fast=fast.next;
slow=slow.next;
}
fast.next = head;
head=slow.next;
slow.next = null;
return head;
}
}