题解 | #复杂链表的复制#

复杂链表的复制

https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba

function RandomListNode(x){
    this.label = x;
    this.next = null;
    this.random = null;
}
function Clone(pHead)
{
    // write code here
    if (pHead === null) return null
    const targetCache = []
    const copiedCache = []
    let currentNode = pHead
    const copiedHead = new RandomListNode(pHead.label)
    let currentCopiedNode = copiedHead
    targetCache.push(currentNode)
    copiedCache.push(currentCopiedNode)
    while (currentNode.next) {
        const cachedNodeIndex = targetCache.indexOf(currentNode.next)
        if (cachedNodeIndex === -1) {
            currentCopiedNode.next = new RandomListNode(currentNode.next.label)
            copiedCache.push(currentCopiedNode.next)
        } else {
            currentCopiedNode.next = copiedCache[cachedNodeIndex]
        }

        if (currentNode.random !== null) {
            const cachedRandomNodeIndex = targetCache.indexOf(currentNode.random)
            if (cachedRandomNodeIndex === -1) {
                currentCopiedNode.random = new RandomListNode(currentNode.random.label)
                copiedCache.push(currentCopiedNode.random)
            } else {
                currentCopiedNode.random = copiedCache[cachedRandomNodeIndex]
            }
        }
        currentNode = currentNode.next
        currentCopiedNode = currentCopiedNode.next
        targetCache.push(currentNode)
    }
    return copiedHead
}
module.exports = {
    Clone : Clone
};

全部评论

相关推荐

小叮当411:应该是1-3个月吧
点赞 评论 收藏
分享
05-21 15:47
门头沟学院 Java
浪漫主义的虹夏:项目有亮点吗,第一个不是纯玩具项目吗,项目亮点里类似ThreadLocal,Redis储存说难听点是花几十分钟绝大部分人都能学会,第二个轮子项目也没体现出设计和技术,想实习先沉淀,好高骛远的自嗨只会害了自己
点赞 评论 收藏
分享
陆续:不可思议 竟然没那就话 那就我来吧 :你是我在牛客见到的最美的女孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务