leetcode刷题笔记一百三十八题 复制带随机指针的链表

leetcode刷题笔记一百三十八题 复制带随机指针的链表

源地址:138. 复制带随机指针的链表

问题描述:

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的 深拷贝。

我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:

val:一个表示 Node.val 的整数。
random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为 null 。

输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]

//138题的思路主要参考了133题 克隆图的DFS深拷贝方法
/**
 * Definition for a Node.
 * class Node(var _value: Int) {
 *   var value: Int = _value
 *   var next: Node = null
 *   var random: Node = null
 * }
 */

import scala.collection.mutable
object Solution {
    def copyRandomList(head: Node): Node = {
        if (head == null) return null
        val visited =  mutable.HashMap.empty[Node, Node]

        def helper(node: Node, visited: mutable.HashMap[Node, Node]): Node = {
            if (visited.contains(node)) return visited(node)
        
            val cloneNode = new Node(node.value)
            visited.put(node, cloneNode)

            if (node.next != null) cloneNode.next = helper(node.next, visited)
            if (node.random != null) cloneNode.random = helper(node.random, visited)
            return cloneNode
        }
        helper(head, visited)
    }
}
原文地址:https://www.cnblogs.com/ganshuoos/p/13532514.html