安順住房和城鄉(xiāng)建設(shè)部網(wǎng)站網(wǎng)站app開發(fā)公司
LeetCode講解篇之138. 隨機(jī)鏈表的復(fù)制
文章目錄
- LeetCode講解篇之138. 隨機(jī)鏈表的復(fù)制
- 題目描述
- 題解思路
- 題解代碼
題目描述
題解思路
先遍歷一遍鏈表,用哈希表保存原始節(jié)點(diǎn)和克隆節(jié)點(diǎn)的映射關(guān)系,先只克隆節(jié)點(diǎn)的Val,然后再次遍歷鏈表,根據(jù)哈希表通過(guò)原始節(jié)點(diǎn)的鏈接信息找到克隆節(jié)點(diǎn),然后鏈接克隆節(jié)點(diǎn)
題解代碼
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]
}