LeetCode61 旋转链表

题目

在这里插入图片描述
在这里插入图片描述

解题

解题一:递归

// javascript
var rotateRight = function(head, k) {
    const len = getLength(head);           // 获取长度
    k %= len;                           
    if (k === 0) return head;              // 如果 k 是 len 的倍数,旋转后头节点不变
    const helper = (curNode) => {
        if (curNode === null) return null;
        const nextNode = helper(curNode.next);
        if (k > 0 && nextNode !== null) {  // 依次把非空尾节点设置为新的头节点
            nextNode.next = head;
            head = nextNode;
            curNode.next = null;
            k--;
        }
        return curNode;
    }
    helper(head);
    return head;
};

const getLength = (head) => {
    let len = 0;
    while (head !== null) {
        len++;
        head = head.next;
    }
    return len;
};

时间复杂度: O ( n ) O(n) O(n),需要遍历该链表两次。
空间复杂度: O ( n ) O(n) O(n),递归的深度为链表的长度。

解题二的方法空间复杂度会更优。

解题二:闭合为环

在这里插入图片描述

// javascript
var rotateRight = function(head, k) {
    if (k === 0 || !head || !head.next) return head;
    let len = 1, cur = head;
    while (cur.next) {              // 寻找尾节点,所以是 cur.next,len 初始化为 1 
        len++;
        cur = cur.next;
    }
    let steps = len - (k % len);    // cur 指向尾部,从头部走是 len - 1 - (k % len),从尾部会多一步
    if (steps === len) return head; // 走 len 步会指向原来的 head,直接返回
    cur.next = head;                // 首尾相连
    while (steps > 0) {             // 寻找新的尾部 cur
        cur = cur.next;
        steps--;
    }
    const newHead = cur.next;       // 新的 head
    cur.next = null;                // 首尾断开
    return newHead;
};

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值