反转单向链表

#思路

对于每一个节点,都让自己指向前一个节点,可以用迭代或者递归。

迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const reverseList = function(head) {
let prev = null;
let save = null;

while(head){
save = head.next;
head.next = prev;

prev = head;
head = save;
}

return prev;
};

递归

1
2
3
4
5
6
7
8
9
10
11
const reverseList = reverseList(head) {
if (!head || !head.next) {
return head;
}
const newHead = reverseList(head.next);

head.next.next = head;
head.next = null;

return newHead;
}