61. Rotate List

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        // edge case: number of nodes is 0
        if (head==null) return head;
        
        ListNode first = head;
        int count = 1;
        while (first.next!=null){
            first = first.next;
            count++;
        }
        
        k=k%count;
        
        // edge case: k is 0, or number of nodes is 1
        if (k==0 || count==1) return head;
        
        ListNode second = head;
        while (count-k>1){
            second=second.next;
            count--;
        }
        
        ListNode newHead = second.next;
        second.next=null;
        first.next=head;
        return newHead;
    }
}

Last updated