LeetCode讲解篇之138. 随机链表的复制
文章目录
- LeetCode讲解篇之138. 随机链表的复制
- 题目描述
- 题解思路
- 题解代码
题目描述
题解思路
先遍历一遍链表,用哈希表保存原始节点和克隆节点的映射关系,先只克隆节点的Val,然后再次遍历链表,根据哈希表通过原始节点的链接信息找到克隆节点,然后链接克隆节点
题解代码
func copyRandomList(head *Node) *Node {record := make(map[*Node]*Node, 0)tmp := headfor tmp != nil {record[tmp] = &Node{Val: tmp.Val,}tmp = tmp.Next}tmp = headfor tmp != nil {record[tmp].Next = record[tmp.Next]record[tmp].Random = record[tmp.Random]tmp = tmp.Next}return record[head]
}