Skip to content

Files

Latest commit

37ca6f5 · Oct 19, 2022

History

History
45 lines (39 loc) · 1022 Bytes

0061. Rotate List.md

File metadata and controls

45 lines (39 loc) · 1022 Bytes

Screen Shot 2022-10-14 at 12 49 24 AM

image

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var rotateRight = function(head, k) {
    if(!head) return head;
    let curr = head, count = 0;
    
    while(curr) {
        count++;
        curr = curr.next;
    }
    
    k = k % count;
    let prev = head;
    curr = head;
    
    while(k) {
        curr = curr.next;
        k--;
    }
    
    while(curr.next) {
        prev = prev.next;
        curr = curr.next;
    }
    curr.next = head;
    head = prev.next;
    prev.next = null;
    return head;
};