LeetCode61(2021.3.27)

LC61. 旋转链表

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++;
        }
        if (k % n == 0) {
            return head;
        }
        int add = n - k % n;
        iter.next = head; //成环
        while (add-- != 0) {
            iter = iter.next;
        }
        ListNode res = iter.next;
        iter.next = null;
        return res;
    }
}

留下评论