# 143. 重排链表

var reorderList = function(head) {
  if (head === null) return null;
  const prevHead = { next: head };

  const arr = [];

  while (head) {
    arr.push(head);
    head = head.next;
  }
  head = prevHead.next;
  const n = arr.length - 1;

  const nums = [];
  const is = n % 2;
  const mid = is ? Math.floor(n / 2) : Math.floor(n / 2) - 1;

  for (let i = 0; i <= mid; i++) {
    nums.push(arr[i]);
    nums.push(arr[n - i]);
    if (!is && i === mid) {
      nums.push(arr[mid + 1]);
    }
  }

  for (let i = 1; i < nums.length; i++) {
    head.next = nums[i];
    head = head.next;
  }
  head.next = null;
  console.log(JSON.stringify(prevHead.next));
};
console.log(
  reorderList({
    val: 1,
    next: {
      val: 2,
      next: {
        val: 3,
        next: {
          val: 4,
          next: null,
        },
      },
    },
  })
);
console.log(
  reorderList({
    val: 1,
    next: {
      val: 2,
      next: {
        val: 3,
        next: {
          val: 4,
          next: {
            val: 5,
            next: null,
          },
        },
      },
    },
  })
);
console.log(
  reorderList({
    val: 1,
    next: null,
  })
);
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
64
65
66
67
68
69
70
71
Last Updated: 6/27/2023, 7:40:45 PM