`leetcode - Reverse Linked List @ Thu, Feb 23, 2023 9:10 PM` `leetcode - Reverse Linked List @ Sun, Mar 5, 2023 9:43 PM` `Expand 33 lines ...` `34` ``````function reverseList(head: ListNode | null): ListNode | null { `````` `34` ``````function reverseList(head: ListNode | null): ListNode | null { `````` `35` `````` // base case, breaking recursive loop `````` `35` `````` // base case, breaking recursive loop `````` `36` `````` if (head === null || head.next === null) return head; `````` `36` `````` if (head === null || head.next === null) return head; `````` `37` `+` `````` // head.next.next.next 到 base case, 即最后一个节点(倒数第一个) `````` `37` `````` const newHead = reverseList(head.next); `````` `38` `````` const newHead = reverseList(head.next); `````` `39` `+` `````` // 由于是递归，函数栈一直增加，FILO 其实是从后往前处理的。最后处理第一个节点。 `````` `38` `````` head.next.next = head; `````` `40` `````` head.next.next = head; `````` `39` `````` head.next = null; `````` `41` `````` head.next = null; `````` `40` `````` return newHead; `````` `42` `````` return newHead; `````` `Expand 18 lines ...` `59` ``````function reverseList(head: ListNode | null): ListNode | null { `````` `61` ``````function reverseList(head: ListNode | null): ListNode | null { `````` `60` `````` let prev = null; `````` `62` `````` let prev = null; `````` `61` `````` let cur = head; `````` `63` `````` let cur = head; `````` `64` `+` `````` // 从头开始处理 `````` `62` `````` while (cur !== null) { `````` `65` `````` while (cur !== null) { `````` `66` `+` `````` // 把 next node 存起来 `````` `63` `````` const next = cur.next; `````` `67` `````` const next = cur.next; `````` `68` `+` `````` // 按顺序处理 node，把处理过的加到当前处理 node 的 next 指针上 `````` `64` `````` cur.next = prev; `````` `69` `````` cur.next = prev; `````` `70` `+` `````` // 处理完成的挂到 prev 变量上 `````` `65` `````` prev = cur; `````` `71` `````` prev = cur; `````` `72` `+` `````` // 接下来要处理的，进入下一次循环 `````` `66` `````` cur = next; `````` `73` `````` cur = next; `````` `67` `````` } `````` `74` `````` } `````` `68` `````` return prev; `````` `75` `````` return prev; `````` `Expand 2 lines ...`