【基础篇 - Day 8】 2020-11-08 - 61. 旋转链表(02. 链表)
题目描述
入选理由
- 考察对链表的理解
- 考察环形链表等非常见类型链表题
题目地址
https://leetcode-cn.com/problems/rotate-list/
题目描述
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 1→2→3→4→5→NULL, k = 2
输出: 4→5→1→2→3→NULL
解释:
向右旋转 1 步: 5→1→2→3→4→NULL
向右旋转 2 步: 4→5→1→2→3→NULL
示例 2:输入: 0→1→2→NULL, k = 4
输出: 2→0→1→NULL
解释:
向右旋转 1 步: 2→0→1→NULL
向右旋转 2 步: 1→2→0→NULL
向右旋转 3 步: 0→1→2→NULL
向右旋转 4 步: 2→0→1→NULL来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的回答
解法一
时空复杂度
时间复杂度:O(n)
空间复杂度: O(1)
在后旋转几个其实可以理解成 以第几个为链表头
所以先统计总次数 重复圈数去除,将链表转化成环后 移动 length-k 位即可
var rotateRight = function (head, k) {
if (!head || !head.next) return head
let length = 1
let currList = head
while (currList.next) {
length++
currList = currList.next
}
currList.next = head
let rank = length - k % length
let newHead = null;
while (rank) {
currList = currList.next
rank--
}
newHead = currList.next
currList.next = null
return newHead
};