需要对 javascript 中的递归反向单链表代码进行解释

问题描述

每行都console.log,看过很多 YouTube 视频,但无法理解。 我需要一步一步地了解正在发生的事情。

举个例子,我知道在 if 语句之后的 return head 永远不会被调用,但它应该考虑到每次 newHead 被声明时它都会调用 head.next 作为新的前往 reverseList(head),这应该导致 head.next === null

下面是我的代码:

let headList = {
  value: 1,next: {
    value:2,next: {
      value:3,next: {
        value:4,next: {
          value:5,next: null
        }
      }
    }
  }
}

function reverseList(head) {
    if(head == null || head.next == null) {
        return head
    }

    newHead = reverseList(head.next);

    head.next.next = head;
    
    head.next = null;
    return newHead;

};

reverseList(headList)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)