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.
旋转一个链表,首先我们计算出链表的长度len,如果k % len == 0, 我们可以直接返回head,如果不为0,我们就让head移动 len - 1 - (k % len)次,将链表分为两部分,这样剩下的右边部分就是长度为k的一个链表,然后将后面长度为k的链表连接到左边部分的链表就完成了。代码如下:
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
旋转一个链表,首先我们计算出链表的长度len,如果k % len == 0, 我们可以直接返回head,如果不为0,我们就让head移动 len - 1 - (k % len)次,将链表分为两部分,这样剩下的右边部分就是长度为k的一个链表,然后将后面长度为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) return null;
int sum = 1;
ListNode tem = head;
while(tem.next != null) {
sum ++;
tem = tem.next;
}
k %= sum;
if(k == 0) return head;
int step = sum - k - 1;
ListNode helper = head;
while(step > 0) {
helper = helper.next;
step --;
}
ListNode node = helper.next;
helper.next = null;
tem.next = head;
return node;
}
}