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
.
我们先考虑通用的情况:
对于k, 我们希望找到2个指针,最终能指在3, 5 这个位置,假设指向3的为slow, 指向5的为fast。
那么,newHead = slow.next ( 4 为head了 )
slow.next = null (从3这里断开了)
fast.next = head; ( 5指向原来的head)
这样就能形成:4->5->1->2->3->NULL
了。
如何能找到这样的2个指针。我们首先要明白,这2指针的间距为k。所以:
1. 先让slow, fast 都指向head
2. 让fast先走k步。
3. 让fast 跟 slow 一样走,当fast.next = null 的时候可以停下来了。
在得到通用的情况以后,还有一些边界问题需要解决:
1. head = null
2. k = 0 (此时不需要逆转的)
3. k > list的长度n ( 这个时候要取 k = k % n )
解决了上述这些问题后,就可以了。
复杂度:
时间复杂度:O ( n )
空间复杂度:O ( 1 )
时间:
代码:
public ListNode rotateRight(ListNode head, int k) {
if (head == null) {
return head;
}
int n = listLength(head);
k = k % n;
if (k == 0) {
return head;
}
ListNode fast = head, slow = head;
for (int i = 0; i < k; i++) {
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
ListNode newHead = slow.next;
slow.next = null;
fast.next = head;
return newHead;
}
private int listLength(ListNode head) {
int count = 0;
while (head != null) {
head = head.next;
count++;
}
return count;
}