# 61. 旋转链表

// 给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
var rotateRight = function(head, k) {
  if (k === 0 || !head || !head.next) return head;

  let cur = head,
    length = 1;

  while (cur.next) {
    cur = cur.next;
    length++;
  }
  // 完成闭环
  cur.next = head;

  // 表示结尾的点距离新的开始的点的距离
  k = length - (k % length);

  while (k > 0) {
    cur = cur.next;
    k--;
  }

  const res = cur.next;
  cur.next = null;
  return res;
};

const head1 = {
  val: 0,
  next: {
    val: 1,
    next: {
      val: 2,
      next: null,
    },
  },
};
const head2 = {
  val: 1,
  next: {
    val: 2,
    next: {
      val: 3,
      next: {
        val: 4,
        next: {
          val: 5,
          next: null,
        },
      },
    },
  },
};
const head3 = {
  val: 1,
  next: {
    val: 2,
    next: null,
  },
};
console.log(rotateRight(head1, 4));
console.log(rotateRight(head2, 2));
console.log(rotateRight(head3, 1));
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
Last Updated: 6/27/2023, 7:40:45 PM