LeetCode每日一题:rotate list

问题描述

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;
    }

你可能感兴趣的:(LeetCode每日一题:rotate list)