-
Notifications
You must be signed in to change notification settings - Fork 15
/
fu-za-lian-biao-de-fu-zhi-lcof.go
70 lines (50 loc) · 1.36 KB
/
fu-za-lian-biao-de-fu-zhi-lcof.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package algorithm
/*
原题:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/
剑指 Offer 35. 复杂链表的复制
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
示例 1:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例 2:
输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]
示例 3:
输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]
示例 4:
输入:head = []
输出:[]
解释:给定的链表为空(空指针),因此返回 null。
提示:
-10000 <= Node.val <= 10000
Node.random 为空(null)或指向链表中的节点。
节点数目不超过 1000 。
*/
type Node struct {
Val int
Next *Node
Random *Node
}
func copyRandomList(head *Node) *Node {
if head == nil {
return nil
}
record := make(map[*Node]*Node)
findNode(record, head)
return record[head]
}
func findNode(record map[*Node]*Node, find *Node) *Node {
if find == nil {
return nil
}
if n, ok := record[find]; ok {
return n
}
node := &Node{}
record[find] = node
node.Val = find.Val
node.Next = findNode(record, find.Next)
node.Random = findNode(record, find.Random)
return node
}