[LintCode/LeetCode] Rotate List

490 查看

Problem

Given a list, rotate the list to the right by k places, where k is non-negative.

Example

Given 1->2->3->4->5 and k = 2, return 4->5->1->2->3.

Note

这是一道有故事的题目。
k有多大?其翼若垂天之云,则或长于链表。链表几长?北海也,天池也,其广数千里,则k亦可容于链表也。
故吾必先穷尽链表之长度,如若head为null,抑或其长可为k所整除,则此题不必再做,返回head可也。
而后吾当依除len取余之法,化大k为小k,则指针不致于越界也。后欲寻右起第k结点,令快指针先行数日,及至两指针相距为k,便吟鞭东指,与慢指针策马共进。则快指针行至null时,慢指针可至右起第k处矣。
方是时也,孤灯长夜,指飞键落。如风吹败叶,雨打窗棂。快慢指针亦止于其所焉。此时看官不妨温酒一盏,看那链表翻转,指针易位。那新头目唤作curhead,正是slow所指之人。fast舞动长剑,中宫直入,直取head首级,而slow一掌劈空,null已鸿飞冥冥。
自此,curhead一代天骄,霸业已成。

Solution

public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        ListNode fast = head, slow = head;
        int len = 0;
        while (fast != null) {
            fast = fast.next;
            len++;
        }
        if (head == null || k % len == 0) return head;
        fast = head;
        k = k % len;
        while (k-- > 0) fast = fast.next;
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        ListNode curhead = slow.next;
        slow.next = null;
        fast.next = head;
        return curhead;
    }
}