旋转链表

环形链表,重新找到head节点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    // 得到链表的长度, 和将链表的结尾指向head节点。 形成环形。
    public int getLength(ListNode head ){
        ListNode tmp = head;
        
        int len =1;
        while( tmp.next != null ){
            len++;
            tmp = tmp.next;
        }
        tmp.next = head;
        return len;
    }
    
    public ListNode rotateRight(ListNode head, int k) {
        
        if( head == null )
            return null;
        int len = getLength(head);
        ListNode cur=head;
        k = k % len;  // 求余, 具体是将链表右移多少节点就可以。
        for( int i=1; i < len-k; ++i ){   // 定位到原来link的倒数第k节点。cur
            cur = cur.next;
        }
        
        head = cur.next;  // 重新head
        cur.next = null;

        return head;
    }
}
原文地址:https://www.cnblogs.com/lijins/p/10150452.html