LeetCode | Rotate List

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.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
//关键在于找到旋转节点pivot,pivot.next成为新的头,pivot成为新的尾,而原list的尾后面接上原list的头
public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        
        if(head==null) return head;
        
        int length = 0;
        ListNode myNode = head;
        while(myNode != null){              //利用循环求得list的长度
            length++;
            myNode = myNode.next;
        }
        
        if(k >= length) k = k % length;    //此处注意,k是有可能大于长度的
        if(length<=1 || k==0) return head; //此两种情况都不用旋转,直接返回即可
        
        int pivot = length - 1 - k;        //旋转点位置,题目示例中,pivot=2,代表list中第三个节点
        ListNode newHead = null;
        myNode = head;                     //重复利用myNode
        for(int i=0; i<length; i++){
            if(i == pivot){
                newHead = myNode.next;     //新的头
                myNode.next = null;        //新的尾
                myNode = newHead;          //让for循环继续下去
            }
            if(myNode.next != null){       //过了pivot也让循环继续下去,是为了取得原先list的尾
                myNode = myNode.next;
            }
        }
        myNode.next = head;                //此时,myNode为原list的尾,将其接上原list的head
        
        return newHead;
    }
}


原文地址:https://www.cnblogs.com/dosmile/p/6444419.html