题目

https://leetcode-cn.com/problems/reverse-linked-list/

解题

  1. /**
  2. * Definition for singly-linked list.
  3. * function ListNode(val, next) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.next = (next===undefined ? null : next)
  6. * }
  7. */
  8. /**
  9. * @param {ListNode} head
  10. * @return {ListNode}
  11. */
  12. var reverseList = function(head) {
  13. if (head === null) {
  14. return null
  15. }
  16. // 第一种、迭代
  17. // const stack = []
  18. // let current = head
  19. // while(current) {
  20. // stack.push(current.val)
  21. // current = current.next
  22. // }
  23. // for (let i = stack.length - 1; i >= 0; i--) {
  24. // if (i === stack.length - 1) {
  25. // head = current = new ListNode(stack[i])
  26. // } else {
  27. // current.next = new ListNode(stack[i])
  28. // current = current.next
  29. // }
  30. // }
  31. // return head
  32. // 第二种 、递归
  33. const recursion = (node) => {
  34. if (node.next === null) {
  35. head = node
  36. return node
  37. }
  38. const prev = recursion(node.next)
  39. prev.next = new ListNode(node.val)
  40. return prev.next
  41. }
  42. recursion(head)
  43. return head
  44. };