two pointers - Java


  • 0
    F
        public ListNode rotateRight(ListNode head, int k) {
            if (head == null || k == 0) return head;
    
            ListNode first = head;
            ListNode second = head;
    
            int i = 0;
            while (i < k && first.next != null) {
                first = first.next;
                i++;
            }
    
            if (first.next == null && i < k) {
                return rotateRight(head, k%(i+1));
            }
    
            while (first.next != null) {
                first = first.next;
                second = second.next;
            }
    
            ListNode returned = second.next;
            first.next = head;
            second.next = null;
    
            return returned;
        }
    

Log in to reply
 

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