Orion's Studio.

算法(9)-反转链表

2024/03/10

题目(easy):

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

思路

再定义个新的链表是对空间的浪费,所以直接用双指针法反转链表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const reverseList = (head) => {
if (!head || !head.next) {
return head;
}
let temp = null;
let pre = null;
let cur = head;
while(cur) {
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
CATALOG
  1. 1. 题目(easy):
  2. 2. 思路