blog
blog copied to clipboard
[LeetCode] linked list
反转链表
递归
var reverseList = function(head) {
if (!head.next || !head ) return head // if console.log will get 1,2,3,4,5
const prev = reverseList(head.next)
head.next.next = head // if console.log here will get 5,4,3,2,1
head.next = null
return prev
};
双指针
var reverseList = function(head) {
let prev = null
let curr = head
while(curr) {
let temp = curr.next
curr.next = prev
prev = curr
curr = temp
}
return prev
};