Skip to content

Commit 2e39614

Browse files
committed
1 parent 852a5bb commit 2e39614

File tree

1 file changed

+84
-0
lines changed
  • src/main/kotlin/leetcode/copy-list-with-random-pointer

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package leetcode.`copy-list-with-random-pointer`
2+
3+
class Solution {
4+
fun copyRandomList(node: Node?): Node? {
5+
node ?: return null
6+
var p = node
7+
while (p != null) {
8+
val copyP = Node(p.`val`)
9+
copyP.next = p.next
10+
p.next = copyP
11+
p = copyP.next
12+
}
13+
p = node
14+
while (p != null) {
15+
p.next?.random = p.random?.next
16+
p = p.next?.next
17+
}
18+
p = node
19+
var oldNode: Node? = null
20+
var result: Node? = null
21+
var copyP = result
22+
var count = 0
23+
while (p != null) {
24+
if (count % 2 == 0) {
25+
if (oldNode == null) {
26+
oldNode = p
27+
} else {
28+
oldNode.next = p
29+
oldNode = oldNode.next
30+
}
31+
} else {
32+
if (result == null) {
33+
result = p
34+
copyP = result
35+
} else {
36+
copyP?.next = p
37+
copyP = copyP?.next
38+
}
39+
}
40+
count++
41+
p = p.next
42+
}
43+
oldNode?.next = null
44+
copyP?.next = null
45+
return result
46+
}
47+
48+
49+
//O(N)
50+
// fun copyRandomList(node: Node?): Node? {
51+
// node ?: return null
52+
// var p = node
53+
// var head: Node? = null
54+
// val map = hashMapOf<Node, Node?>()
55+
// var copyP: Node? = null
56+
// while (p != null) {
57+
// if (head == null) {
58+
// head = Node(p.`val`)
59+
// copyP = head
60+
// map[p] = head
61+
// } else {
62+
// val copyNode = Node(p.`val`)
63+
// map[p] = copyNode
64+
// copyP?.next = copyNode
65+
// copyP = copyP?.next
66+
// }
67+
// p = p.next
68+
// }
69+
// p = node
70+
// copyP = head
71+
// while (p != null) {
72+
// copyP?.random = map[p.random]
73+
// copyP = copyP?.next
74+
// p = p.next
75+
// }
76+
// return head
77+
// }
78+
}
79+
80+
81+
class Node(var `val`: Int) {
82+
var next: Node? = null
83+
var random: Node? = null
84+
}

0 commit comments

Comments
 (0)