Rotate List

Given a list, rotate the list to the right bykplaces, where_k_is non-negative.

Example

Given1->2->3->4->5and k =2, return4->5->1->2->3.

public ListNode rotateRight(ListNode head, int k) {
    if(head == null || head.next == null) {
        return head;
    }
    int len = 0;
    ListNode p = head;
    while(p != null) {
        len++;
        p = p.next;
    }
    k = k % len;
    if(k == 0) {
        return head;
    }
    ListNode fast = head, slow = head;
    for(int i = 0; i < k; i++) {
        fast = fast.next;
    }
    while(fast.next != null) {
        slow = slow.next;
        fast = fast.next;
    }
    ListNode l1 = head, l2 = slow.next;
    fast.next = l1;
    slow.next = null;
    return l2;
}

results matching ""

    No results matching ""