Problem
Given a list, rotate the list to the right by k places, where k is non-negative.
Example
Given 1->2->3->4->5 and k = 2, return 4->5->1->2->3.
思路
错误的思路
- find the len
- split the list from the last second place
- append left part to the end of right part
错误原因:
当 k > len的时候, 应该继续从右到左数
所以加上 k %= len
public ListNode rotateRight(ListNode head, int k) {
// 1. find the len
ListNode curt = head;
int len = 1;
while (curt != null && curt.next != null) {
curt = curt.next;
len++;
}
ListNode lastNode = curt;
k %= len;
if (k == 0) return head;
// 2. split the list from the last second place
curt = head;
ListNode prev = null;
for (int i = 1; i <= len - k; i++) {
prev = curt;
curt = curt.next;
}
prev.next = null;
// 3. append left part to the end of right part
lastNode.next = head;
return curt;
}