/**61. Rotate List
* @param head
* @param k
* @return 成环后右移k位
*/
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0) {
return head;
}
ListNode cur = head;
int len = 0;
while (cur != null) {
cur = cur.next;
len += 1;
}
k = k%len;
if(k == 0)
return head;
ListNode ret = new ListNode(-1);
ListNode fast = head;
ListNode fastPre = ret;
ListNode slow = head;
ListNode slowPre = ret;
int count = 0;
while (fast != null) {
if (count < k) {
count += 1;
} else {
slowPre = slow;
slow = slow.next;
}
fastPre = fast;
fast = fast.next;
}
if (slow == head) {
return head;
} else {
slowPre.next = null;
ret.next = slow;
fastPre.next = head;
return ret.next;
}
}
/**循环后移k>len,要取余
* 之后fast,slow隔开k位直到fast走到队尾,slow就是新链表的头,拼接
* */
还可以成环之后,移动