Rotate List(回転チェーンテーブル)

1365 ワード

に質問
Given a list, rotate the list to the right by k places, where k is non-negative.
Have you met this question in a real interview? Yes Example Given 1->2->3->4->5 and k = 2, return 4->5->1->2->3.
ぶんせき
まずチェーンテーブルの全長を算出し,オフセット量Kは実際には最後のK個の長さを前に置くことが理解できる.だから後ろのK個の長さの前の位置を見つけて、ポインタを修正すればいいです.
コード#コード#
/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode(int x) {
 * val = x;
 * next = null;
 * }
 * }
 */


public class Solution {
    /*
     * @param head: the List
     * @param k: rotate to the right k places
     * @return: the list after rotation
     */
    public ListNode rotateRight(ListNode head, int k) {
        int n = 0;
        ListNode tail = head;
        while (tail != null) {
            n++;
            if (tail.next == null) {
                break;
            }
            tail = tail.next;
        }
        if (n < 2) {
            return head;
        }
        k = k % n;
        if (k==0){
            return head;
        }
        ListNode newHead = head;
        int temp = 1;
        while (temp < n - k) {
            newHead = newHead.next;
            temp++;
        }
        ListNode node = newHead.next;
        newHead.next = null;
        tail.next = head;
        return node;
    }
}