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 ,旋转列表最后 k 个元素至列表最前面。
思路:
- 先找到最后元素 lastOne ,并计算链表长度,同时最后一个元素指向头节点,形成一个环。
- 从head节点开始,往后走到第 len - k % len,即走到了旋转后列表新的最后元素 newLastOne,新的环链表在newLastOne之后断开。
- 断开的链表即是反转后的新链表。
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0) return head;
ListNode p = head;
int len = 1;
while (p.next != null) {
len++;
p = p.next;
}
p.next = head;//form a cycle List
for (k = len - k % len; k > 0; k--) p = p.next;
head = p.next;//break the circle at the (len - k % len)th ListNode
p.next = null;
return head;
}