Leetcode 题目解析之 Rotate List

2022-01-15 12:06:38 浏览数 (1)

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

For example:

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

return 4->5->1->2->3->NULL.

代码语言:javascript复制
    public ListNode rotateRight(ListNode head, int k) {

        if (head == null)
            return null;

        int len = 1;

        ListNode tail = head;

        while (tail.next != null) {
            len  ;
            tail = tail.next;
        }

        tail.next = head; // cycle

        k %= len;

        for (int i = 1; i < len - k; i  ) {
            head = head.next;
        }

        try {
            return head.next;
        } finally {
            head.next = null; // cut
        }
    }

0 人点赞