forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
49 lines (45 loc) · 900 Bytes
/
Solution.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
/**
* Definition for a Node.
* type Node struct {
* Val int
* Next *Node
* Random *Node
* }
*/
func copyRandomList(head *Node) *Node {
if head == nil {
return nil
}
cur := head
for cur != nil {
node := &Node{
Val: cur.Val,
Next: cur.Next,
Random: nil,
}
cur.Next = node
cur = node.Next
}
cur = head
for cur != nil {
if cur.Random == nil {
cur.Next.Random = nil
} else {
cur.Next.Random = cur.Random.Next
}
cur = cur.Next.Next
}
copy := head.Next
cur = head
for cur != nil {
next := cur.Next
cur.Next = next.Next
if (next.Next == nil) {
next.Next = nil
} else {
next.Next = next.Next.Next
}
cur = cur.Next
}
return copy
}