LeetCode: Copy List With Random Pointer Solution

1/**
2 * // Definition for a Node.
3 * function Node(val, next, random) {
4 * this.val = val;
5 * this.next = next;
6 * this.random = random;
7 * };
8 */
9
10/**
11 * @param {Node} head
12 * @return {Node}
13 */
14var copyRandomList = function (head) {
15 let newHead
16 let iter
17 let prevIter
18
19 iter = head
20 while (iter) {
21 const node = new Node(iter.val)
22
23 if (prevIter) {
24 prevIter.next = node
25 } else {
26 newHead = node
27 }
28
29 prevIter = node
30 iter.newRef = node
31 iter = iter.next
32 }
33
34 iter = head
35 while (iter) {
36 iter.newRef.random = iter.random?.newRef
37 iter = iter.next
38 }
39
40 return newHead
41}

Comments

Loading comments...

Tags

leetcode

linked list

hash table

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Number Of Steps To Reduce A Number To Zero

HoningJS

Search Posts