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
.
方法一:假设链表长度为N,倒数第k处节点,对应正数第N+1-k处节点。只需要将链表从N-k处断开成两个链表[1, N-k], [N-k+1, N],然后将前面部分的链表追加到后部分链表尾部即可。现在的关键就是找到这个N-k处节点。
考虑到k会大于链表的长度,用链表长度N对k做求余运算,k = k % N,
1. 遍历计算链表长度:N,在遍历时注意保存最后一个节点的引用,在重新连接链表时需要使用;
2. 遍历找到N-k处的节点;
3. 在N-k处分割链表,再重新连接链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
ListNode tail = head;
int length = 0;
while (tail.next != null) {
++length;
tail = tail.next;
}
length = length + 1;
k = k % length;
if (k == 0) {
return head;
}
ListNode splitNode = head;
int splitIndex = length - k - 1;
while (splitIndex-- != 0) {
splitNode = splitNode.next;
}
tail.next = head;
head = splitNode.next;
splitNode.next = null;
return head;
}
}