通过迭代方式

  1. function reverseList(head) {
  2. // a -> b -> c -> null
  3. // c -> b -> a -> null
  4. let prev = null;
  5. let cur = head;
  6. while (cur) {
  7. const next = cur.next; // 获取下一个节点
  8. cur.next = prev; // 当前节点指向上一个节点
  9. prev = cur; // 存储上一个节点
  10. cur = next; // 更新当前节点
  11. }
  12. return prev;
  13. }

通过递归方式

  1. function reverseList(head) {
  2. // a -> b -> c -> null
  3. // c -> b -> a -> null
  4. if (!head || !head.next) {
  5. return head; // 返回最里面的一个节点
  6. }
  7. const newHead = reverseList(head.next);
  8. // 从内到外执行(获取最里面的一个节点)
  9. head.next.next = head;
  10. head.next = null; // 解除环引用
  11. return newHead;
  12. }