旋转链表(中等)

旋转链表(中等)_第1张图片

将链表闭合为环,然后根据旋转的位置大小来找到需要断开的地方。

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (k == 0 || head == null || head.next == null) {
            return head;
        }
        int n = 1;
        ListNode iter = head;
        while (iter.next != null) {
            iter = iter.next;
            n++;
        }
        int kk = k % n;
        if (kk == 0) {
            return head;
        }
        iter.next = head; // 形成环
        ListNode newTail = head;
        for (int i = 0; i < n - kk - 1; i++) {
            newTail = newTail.next;
        }
        ListNode newHead = newTail.next;
        newTail.next = null; // 断开环
        return newHead;
    }
}

你可能感兴趣的:(链表,数据结构)