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可以大于列表中元素个数,此时k=k%num;(num为列表中元素个数)
解题思路:
1.计算列表长度,即元素个数num。
2.循环找到第num-k个元素和第num-k+1个元素,并将第num-k个元素的next值置为null。
3.从第num-k+1个元素开始循环,直到列表末尾元素,将其next值置为head(head为列表头元素)。
4.返回第num-k+1个元素。完成!
下面贴代码:
/**
* 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) {
int num= 0;
ListNode h = head; //计算列表长度
while(h != null){
num++;
h = h.next;
}
if(num<2) return head;
k = k%num; //计算k的值
if(k==0 || k==num) return head;
ListNode h1 = head;
for(int i=0;i<num-k-1;i++){ //找到第num-k个元素
h1 = h1.next;
}
h = h1.next; //第num-k+1个元素
h1.next = null;
h1 = h;
while(h1.next != null){ //找到末尾元素
h1 = h1.next;
}
h1.next = head;
return h;
}
}