Skip to content

Commit ec6da5b

Browse files
authored
Merge pull request neetcode-gh#1300 from voski/patch-10
Create 0138-Copy-List-With-Random-Pointer.rb
2 parents 2523409 + f8ffe6d commit ec6da5b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Definition for Node.
2+
# class Node
3+
# attr_accessor :val, :next, :random
4+
# def initialize(val = 0)
5+
# @val = val
6+
# @next = nil
7+
# @random = nil
8+
# end
9+
# end
10+
11+
# @param {Node} node
12+
# @return {Node}
13+
def copyRandomList(head)
14+
copies = {}
15+
16+
curr = head
17+
while curr
18+
copies[curr] = Node.new(curr.val)
19+
curr = curr.next
20+
end
21+
22+
curr = head
23+
while curr
24+
copies[curr].next = copies[curr.next]
25+
copies[curr].random = copies[curr.random]
26+
curr = curr.next
27+
end
28+
29+
copies[head]
30+
end

0 commit comments

Comments
 (0)