61\. 旋转链表

# 61. 旋转链表 (opens new window)

# Description

Difficulty: 中等

Related Topics: 链表 (opens new window), 双指针 (opens new window)

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k个位置。

示例 1:

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
1
2

示例 2:

输入:head = [0,1,2], k = 4
输出:[2,0,1]
1
2

提示:

  • 链表中节点的数目在范围 [0, 500]
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 109

# Solution

Language: JavaScript

/**
 * 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 (k === 0 || !head || !head.next) {
        return head
    }

    let len = 1
    let cur = head
    while (cur.next) {
        cur = cur.next
        len++;
    }

    cur.next = head
    k = len - k % len
    
    while (k--) {
        cur = cur.next
    }
    head = cur.next
    cur.next = null
    return head
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
上次更新: 2022/8/31 下午9:04:12