Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULLOutput: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
prev cur next1 -> 2 -> 3 -> 4 -> 5 -> nullnull <- 1 -> 2 -> 3 -> 4 -> 5
step:
/*** Definition for singly-linked list.* function ListNode(val) {* this.val = val;* this.next = null;* }*//*** @param {ListNode} head* @return {ListNode}*/var reverseList = function(head) {let prev = nulllet cur = headif (head) {let next = head.nextwhile (cur.next) {cur.next = prevprev = curcur = nextnext = next.next}cur.next = prev}return cur};
这样写存在一些冗余的代码, 比如需要判断 head 是否为空, 同时因为 while 中的条件是 cur.next, 因为末尾的 cur.next 需要单独处理一遍, 比较麻烦, 因此进而优化。
/*** @param {ListNode} head* @return {ListNode}*/var reverseList = function(head) {let prev = nulllet cur = headwhile (cur !== null) {let next = cur.nextcur.next = prevprev = curcur = next}return prev};
根据题目的建议, 接着用递归的方式实现一遍(值得注意的是, 迭代与递归的写法都是能互相转换的。)
/*** @param {ListNode} head* @return {ListNode}*/var reverseList = function(head) {let prev = nulllet cur = headconst recursiveFn = () => {if (cur === null) returnlet next = cur.nextcur.next = prevprev = curcur = nextrecursiveFn()}recursiveFn()return prev};
92