Leetcode题解之 —— 反转链表

思路


思路一: 转化为数组

  • 利用reverse反转

思路二: 双指针迭代

  • prev指针存储上一个节点
  • current迭代循环

题解


数组法:

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
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
// TODO solution 1
const cache = [];
let current = head;

while (current) {
cache.push(new ListNode(current.val));
current = current.next;
}

if (!cache.length) {
return null;
}

cache.reverse();

for (const [index, node] of cache.entries()) {
node.next = cache[index + 1];
}

return cache[0];
};

双指针法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let prev = null;
let current = head;

while (current) {
const next = current.next;
current.next = prev;
prev = current;
current = next;
}

return prev;
};