rotate list

Given a list, rotate the list to the right by k places, where k is non-negative.

Example:

Given 1->2->3->4->5->NULL and k = 2,

return 4->5->1->2->3->NULL.

题目是要求从后往前的第k个节点旋转。这里的4.
我们要做的就是:1、将一个指针移到最后节点。2、将另一个指针移到旋转点的前一个节点。这样再更改next的值就可以连接成新链表。
在1中,顺便统计个数,然后根据k,从前往后移到旋转点前一个,移动到旋转点前一个,就得知道该节点从前往后是多少个。旋转点前一个节点位置:总个数-k%总个数。。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    //按右边第k个位置转
    public ListNode rotateRight(ListNode head, int k) {
        if(head==null||k==0||head.next==null) return head;
        
        ListNode fast=head,slow=head;
        int i;
        //统计链表节点总个数
        for( i=1;fast.next!=null;i++)
            fast=fast.next;
        
        //将fast移到旋转节点前一个节点处..如,这里按4旋转,移到3处。
        for(int j=i-k%i;j>1;j--)
            slow=slow.next;
        
        fast.next=head;
        head=slow.next;
        slow.next=null;
        return head;
    }
}
原文地址:https://www.cnblogs.com/xiaolovewei/p/8213479.html