206. 反转链表

  1. 利用外部空间:将所给链表存到ArryList里面或者是新的链表里面,然后再反转动态数组就可以了。
  2. 快慢指针
  3. 递归解法

    代码实现

    js

    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. let prev = null;
    14. let curr = head;
    15. while (curr) {
    16. const next = curr.next;
    17. curr.next = prev;
    18. prev = curr;
    19. curr = next;
    20. }
    21. return prev;
    22. };

    递归实现

    1. /**
    2. * public class ListNode {
    3. * int val;
    4. * ListNode next;
    5. * ListNode(int x) { val = x; }
    6. * }
    7. */
    1. // 避免陷入死循环
    2. if (head == null || head.next == null) return head;
    3. ListNode newHead = reverseList(head.next); //此处递归,找到最后一个节点了
    4. head.next.next = head; //重新指定节点指向(有两个next,注意少写)
    5. head.next = null; //将最初的节点指向空
    6. return newHead; //返回新的“倒置”头节点

    快慢指针

    1. class Solution {
    2. public ListNode reverseList(ListNode head) {
    3. // 避免陷入死循环
    4. if (head == null || head.next == null) return head;
    5. ListNode newHead = null;
    6. while (head != null){
    7. ListNode tmp = head.next;
    8. head.next = newHead;
    9. newHead = head;
    10. head = tmp;
    11. }
    12. return newHead;
    13. }
    14. }