【问题标题】:Issues with reverse Linked List using recursion使用递归的反向链表问题
【发布时间】:2019-01-09 11:44:23
【问题描述】:

我正在尝试使用递归来反转链表。一切都很顺利,直到最后,我最终得到了破碎的结果。

谁能告诉我我做错了什么?

const reverseLinkedList = (node, newChildOldParent=null ) => {
    if( node.next ){
        reverseLinkedList(node.next, node);
    }
    node.next = newChildOldParent;
    return node;
}

const someList = {
    value: 1,
    next: {
        value: 2,
        next: {
            value: 3,
            next: {
                value: 4,
                next: null
            }
        }
    }
};

console.log(reverseLinkedList( someList ))

我明白了

{ value: 1, next: null }

而不是反向链表。

我哪里错了?

【问题讨论】:

  • debugger;@FrankerZ :)
  • console.log() 是永远的
  • 您的问题是您可以颠倒列表,但最终您会再次获得第一个元素(随着堆栈的展开)。您的第一个元素现在是最后一个元素,并且没有 next 节点。
  • 感谢@Sandro 的回复。感谢您的时间。
  • @technoCorner 不客气 :)

标签: javascript algorithm recursion linked-list singly-linked-list


【解决方案1】:

反转工作正常,但是您丢失了新磁头,而是返回了现在指向null 的旧磁头。这是堆栈调用的图表:

curr: 1 next: 2
  curr: 2 next: 3
    curr 3: next: 4
      curr: 4 next: null
      curr: 4 next: 3
    curr: 3 next: 2
  curr: 2 next: 1
curr: 1 next: null <-- uh oh

您需要跟踪新的头,即节点 4。这是将最后一个节点传回头的另一种方法:

const reverseLinkedList = (curr, prev) => {
    if (curr.next) {
        const newHead = reverseLinkedList(curr.next, curr);
        curr.next = prev;
        return newHead; // pass the new head up the list
    }
    
    curr.next = prev;
    return curr; // base case; return the tail
};

const someList = {
    value: 1,
    next: {
        value: 2,
        next: {
            value: 3,
            next: {
                value: 4,
                next: null
            }
        }
    }
};

console.log(reverseLinkedList(someList));

【讨论】:

  • 称它为newHead 而不是next 可能更合适
  • “下一个节点的(列表)”,是的,为什么不呢。但它不是下一个节点,所以很混乱。
  • 我明白你在这里所说的并同意你的看法——我会更新以澄清。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 2011-12-19
  • 2013-03-04
  • 1970-01-01
相关资源
最近更新 更多