/**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就是新鏈表的頭,拼接
* */
還可以成環之後,移動