每日算法 -- 链表'
138. 复制带随机指针的链表
分析
- 主要是分析题目,这里主要多了一个 random 指针是随机的,它可能指向你还没有拷贝好的节点,
- 所以需要额外的空间先存好所有半成品节点,然后再来处理
- map 可以以任意类型作为 key 值,是比较方便的数据结构
- 所以第一次循环,先创建半成品的节点
- 第二次循环的时候给半成品节点配置 next 指针和 random 指针
- 最后返回头节点对应的节点即可。
// 138. 复制带随机指针的链表
// https://leetcode-cn.com/problems/copy-list-with-random-pointer/
/**
* // Definition for a Node.
* function Node(val, next, random) {
* this.val = val;
* this.next = next;
* this.random = random;
* };
*/
var copyRandomList = function(head) {
if(!head) return null
let map = new Map()
let cur = head
// 用 map 存储, key 为老节点,value 为新节点的
while(cur){
map.set(cur,new Node(cur.val))
cur= cur.next
}
cur =head
// 第二次遍历的时候,所有节点都已经拷贝在 map 中了,但是他们还没有 next 和 random
while(cur){
map.get(cur).next = map.get(cur.next) || null
map.get(cur).random = map.get(cur.random) || null
cur= cur.next
}
// 最后返回值 head 的节点
return map.get(head)
};
本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情