LeetCode毎日1題:rotate list

1019 ワード

問題の説明
Given a list, rotate the list to the right by k places, where k is non-negative. For example: Given1->2->3->4->5->NULLand k =2, return4->5->1->2->3->NULL.
もんだいぶんせき
この問題は面倒で、nは大きいかもしれません.余分を取ってから境界点を確定する必要があります.チェーンテーブルの操作には難点はありません.
コード実装
public ListNode rotateRight(ListNode head, int n) {
        if (head == null) return null;
        ListNode tmp = head;
        int len = 0;
        while (tmp != null) {
            len++;
            tmp = tmp.next;
        }
        n = n % len;
        if (n == 0) return head;
        ListNode cur, fast, slow;
        cur = fast = slow = head;
        for (int i = 0; i < n; i++) {
            if (fast != null) fast = fast.next;
            else return null;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        ListNode newHead = slow.next;
        slow.next = null;
        fast.next = cur;
        return newHead;
    }