【leetcode】206. 反转链表

67 阅读1分钟

leetcode-206.png

递归

var reverseList = function (head) {
    if (!head || !head.next) return head
    let newHead = reverseList(head.next)
    // 使当前节点的下一个节点,反过来指向自己
    head.next.next = head
    // 当前节点的前一节点置空
    head.next = null
    return newHead
};
递归过程详细模拟
  1. 初始状态

    链表为:1 -> 2 -> 3 -> null

    初始调用:reverseList(1)

  2. 第一层递归

    • head 为节点 1,head.next 为节点 2
    • 递归调用:reverseList(2)
  3. 第二层递归

    • head 为节点 2,head.next 为节点 3
    • 递归调用:reverseList(3)
  4. 第三层递归

    • head 为节点 3,head.next 为 null
    • 返回 head,即返回节点 3
  5. 第二层返回

    • 当前 head 为节点 2
    • newHead 为节点 3(上一步返回的结果)
    • 操作:head.next.next = head2.next.next = 2),即 3.next = 2
    • 操作:head.next = null,即 2.next = null
    • 返回 newHead,即节点 3

    链表状态:3 -> 2 -> null

  6. 第一层返回

    • 当前 head 为节点 1
    • newHead 为节点 3(上一步返回的结果)
    • 操作:head.next.next = head,即 2.next = 1
    • 操作:head.next = null,即 1.next = null
    • 返回 newHead,即节点 3

    链表状态:3 -> 2 -> 1 -> null

图解.png

非递归

var reverseList = function (head) {
    // 记录前一节点
    let pre = null
    // 当前节点
    let current = head
    while (current) {
        // 保存下一节点
        let nextNode = current.next
        // 实现翻转
        current.next = pre
        // 挪动pre到下一节点,以便下次循环指向
        pre = current
        // 挪动current到下一节点
        current = nextNode
    }
    // current肯定会到最后一个节点,pre 最终被赋值 current,current 最终被赋值 null
    return pre
};