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个位置旋转链表,要求非负值,如上所例。
分析:由于是从右边开始,1)循环获取列表大小size,并且找到列表的尾部 2)然后计算继续所需迭代次数(n = size - k%size)3)最后重新设置列表头和列表尾部。
概括起来,本题不难,不过很容易算错2),由于题目中k的唯一限制是非负值,没有说明是否大于列表。
相应的Java源代码如下。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if(head == null) return null;
int size = 1;
ListNode tail = head;
while(tail.next != null){
tail = tail.next;
size++;
}
tail.next = head;
int nct = size - n % size;
while(nct > 0){
tail = tail.next;
nct--;
}
head = tail.next;
tail.next = null;
return head;
}
}