JS力扣刷题61. 旋转链表

var rotateRight = function(head, k) {
    //计算链表的长度
    let h = head;
    let len = 0;
    while(h){
        len++;
        h = h.next;
    }
    //长度为0和1时直接返回
    if(len == 0 || len == 1)return head;
    //对k取余
    k = k % len;
    //向后移动一位返回新head
    function move(head){
        let q = new ListNode();
        q.next = head;
        while(q.next.next)q = q.next;
        q.next.next = head;
        head = q.next;
        q.next = null;
        return head;
    }
    //向后移动
    for(let i = 0; i < k; i++)
        head = move(head);
    return head;
};

你可能感兴趣的:(力扣刷题,js刷题,链表,javascript,leetcode)