【题目】
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-k个元素变成新head,最后一个元素链接当前的head
注意起始边缘条件,如果head是空,只有一个元素,或者k=0,都只要返回head就可以。
首先找到这个list的长度 n, 方法就是遍历一遍咯。
得到长度以后,我们就知道是哪后几个挪过来。
注意细节!!:
k的值有可能大于n!! 所以 step = n - n%k,
找到最后一个元素之后,最后一个元素就可以直接连接到head了
这时候可以继续用h这个变量,因为已经连接上head了,而且位置在head之前,正好!可以经过step步以后达到新head的前一个,然后把h .next赋给新的headNode,在变成空。(因为队尾下一个要赋值为空!)就OK了!
【代码】
/**
* 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 || k ==0) return head;
ListNode h = head;
int n = 1;
while(h.next != null){
n++;
h = h.next;
}
<span style="background-color: rgb(255, 255, 153);"> h.next = head;</span>
int step = n - k%n;
for(int i = 0 ; i <step;i++){
h = h.next;
}
ListNode NHead = h.next;
h.next = null;
return NHead;