这个反向链表代码有什么问题?

what is wrong with this reverse linklist code?

 var reverseList = function(head) {
    function reverse(cur,pre){
        if(!cur) return pre
        next = cur.next
        cur.next = pre
        return reverse(next,head)
    }
    return reverse(head.next,head)
}

我尝试用递归的方式来写这个,

此代码输出不正确running,此代码有什么问题?

这是我的想法:

如果我们按照您的逻辑假设这种情况 (1->2->3->null),那么最终结果是 - 第一个节点在其 'next' 和第二个节点中具有第二个节点的地址节点在其 'next' 中的地址为 first。因此,形成了一个循环(1->2 和 2->1)。如果要打印这样的列表,在网络平台上会出现死循环的情况。

正如 Thomas Mailund 正确指出的那样,还需要涵盖空列表的情况。

我还建议您将变量名彼此区分,以免混淆。

(例如,您在已用于链表的内部函数中使用 'next' 作为变量名)。

考虑到这些因素,这里是您的代码的修正工作版本:

var reverseList = function(head) {

    var r = null;

    function reverse(p, q) {
        
    q.next = r;

    r = q;

    if (p == null) return q;

    return reverse(p.next, p);

    }

    return (!head) ? head : reverse(head.next,head)

}