讨论/《链表》 - 反转链表/
《链表》 - 反转链表

JavaScript版本~

创建一个假头,将新的节点不断插入到假头的后一个节点,感觉相对好理解一点

var reverseList = function (head) {
    const dummy = new ListNode()
    let cur = head
    while (head) {
        cur = head
        head = head.next
        cur.next = dummy.next
        dummy.next = cur
    }
    return dummy.next
};

递归版本

var reverseList = function (head) {
    if (!head) return head
    const dummy = new ListNode()
    dummy.next = head
    let cur = dummy
    //用于递归的方法
    const dfs = (node) => {
        if (node && !node.next) return node //退出条件
        let newNode = dfs(node.next)
        cur.next = newNode
        newNode.next = null
        cur = cur.next
        return node
    }
    dfs(dummy)
    return dummy.next
};
1
展开全部 21 讨论