Java 14ms, Beats 97.26%


  • 0
    K

    class Solution {

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null || k == 0) {
            return head;
        }
        int len = 0;
        ListNode pre = null, tail = head;
        
        while (tail != null) {
            pre = tail;
            tail = tail.next;
            len++;
        }
        
        pre.next = head;
        tail = head;
        k = (len - k % len) % len;
        
        while (k-- > 0) {
            pre = tail;
            tail = tail.next;
        }
        pre.next = null;
        return tail;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.