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->nullptr and k = 2, return 4->5->1->2->3->nullptr.
这道题思路很巧妙,将尾节点next 指针指向首节点,形成一个环,接着往后跑len-k 步,从这里断开,就是要求的结果了。在实际中,我们选用两个指针,一个比另一个滞后K位即可。
public static void solution_2_2_6(Node head,int k){
Node p1=head,p2=head;
for(int i=1;i<=k;i++){
p2=p2.next;
}
while(p2.next!=null){
p1=p1.next;p2=p2.next;
}
p2.next=head;
Node h=p1.next;
p1.next=null;
for(Node r=h;r!=null;r=r.next){
System.out.print(r.data+" ");
}
}