反转链表

image.png

  1. class ListNode {
  2. constructor(val, next) {
  3. this.val = val;
  4. this.next = (next === undefined ? null : next);
  5. }
  6. }
  7. let node5 = new ListNode(5, null);
  8. let node4 = new ListNode(4, node5);
  9. let node3 = new ListNode(3, node4);
  10. let node2 = new ListNode(2, node3);
  11. let node1 = new ListNode(1, node2);
  12. var reverseList = function(head) {
  13. if(head == null || head.next == null) return head;
  14. var last = reverseList(head.next);
  15. head.next.next = head;
  16. head.next = null;
  17. return last;
  18. };
  19. var p = reverseList(node1);
  20. var ans = [];
  21. while(p != null) {
  22. ans.push(p.val);
  23. p = p.next;
  24. }
  25. console.log(ans);

image.png