[leetcode]Rotate List

捡个软柿子捏一捏,结果也有不少小坑。1.n可能会比length大(或相等),所以要先%一下;2. 是向右rotate而不是向左,所以先n=len-n

public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        if (head == null) return null;
        int len = 0;
        ListNode node = head;
        while (node != null)
        {
            node = node.next;
            len++;
        }
        n = n % len;
        if (n == 0) return head;
        n = len - n;
        node = head;
        ListNode last = null;
        while (n != 0)
        {
            last = node;
            node = node.next;
            n--;
        }
        last.next = null;
        ListNode end = node;
        while (end.next != null)
        {
            end = end.next;
        }
        end.next = head;
        return node;
    }
}

  

原文地址:https://www.cnblogs.com/lautsie/p/3299102.html