Repository navigation
Expand file tree
/
Copy pathRandomPointerLinkedListCopy.java
More file actions
65 lines (49 loc) · 1.65 KB
/
Copy pathRandomPointerLinkedListCopy.java
File metadata and controls
65 lines (49 loc) · 1.65 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.abn.dsalgos.problems;
import java.util.HashMap;
import java.util.Map;
/*
A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.
For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
https://leetcode.com/problems/copy-list-with-random-pointer/
*/
class Node {
public int val;
public Node next;
public Node random;
public Node() {
}
public Node(int val, Node next, Node random) {
this.val = val;
this.next = next;
this.random = random;
}
}
public class RandomPointerLinkedListCopy {
Map<Node, Node> visitedMap = new HashMap<>();
public Node randomCopy(Node head) {
if (head == null) {
return head;
}
Node oldNode = head;
Node newNode = new Node(oldNode.val, null, null);
visitedMap.put(oldNode, newNode);
while (oldNode != null) {
newNode.next = getNode(oldNode.next);
newNode.random = getNode(oldNode.random);
oldNode = oldNode.next;
newNode = newNode.next;
}
return visitedMap.get(head);
}
private Node getNode(Node node) {
if (node != null) {
if (!visitedMap.containsKey(node)) {
visitedMap.put(node, new Node(node.val, null, null));
}
return visitedMap.get(node);
}
return null;
}
}