<script>
class Node
{
constructor(data)
{
this
.data = data;
this
.next =
this
.random =
null
;
}
}
class LinkedList
{
constructor(head)
{
this
.head = head;
}
push(data)
{
let node =
new
Node(data);
node.next =
this
.head;
this
.head = node;
}
print()
{
let temp =
this
.head;
while
(temp !=
null
)
{
let random = temp.random;
let randomData = ((random !=
null
) ?
random.data : -1);
document.write(
"Data = "
+ temp.data +
", Random data = "
+
randomData +
"<br>"
);
temp = temp.next;
}
}
clone()
{
let origCurr =
this
.head,
cloneCurr =
null
;
let map =
new
Map();
while
(origCurr !=
null
)
{
cloneCurr =
new
Node(origCurr.data);
map.set(origCurr, cloneCurr);
origCurr = origCurr.next;
}
origCurr =
this
.head;
while
(origCurr !=
null
)
{
cloneCurr = map.get(origCurr);
cloneCurr.next = map.get(origCurr.next);
cloneCurr.random = map.get(origCurr.random);
origCurr = origCurr.next;
}
return
new
LinkedList(map.get(
this
.head));
}
}
let list =
new
LinkedList(
new
Node(5));
list.push(4);
list.push(3);
list.push(2);
list.push(1);
list.head.random =
list.head.next.next;
list.head.next.random =
list.head.next.next.next;
list.head.next.next.random =
list.head.next.next.next.next;
list.head.next.next.next.random =
list.head.next.next.next.next.next;
list.head.next.next.next.next.random =
list.head.next;
let clone = list.clone();
document.write(
"Original linked list<br>"
);
list.print();
document.write(
"<br>Cloned linked list<br>"
);
clone.print();
</script>