forked from javadev/LeetCode-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNode.java
More file actions
49 lines (46 loc) · 1.32 KB
/
Node.java
File metadata and controls
49 lines (46 loc) · 1.32 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
package com_github_leetcode.random;
@SuppressWarnings("java:S1104")
public class Node {
public int val;
public Node next;
public Node random;
public Node(int val) {
this.val = val;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("[");
result.append("[");
result.append(this.val);
result.append(",");
if (this.random == null) {
result.append("null");
} else {
result.append(this.random.val);
}
result.append("]");
Node curr = this.next;
while (curr != null) {
result.append(",");
result.append("[");
result.append(curr.val);
result.append(",");
if (curr.random == null) {
result.append("null");
} else {
int randomIndex = 0;
Node indexFinder = this;
while (indexFinder.next != null && indexFinder != curr.random) {
randomIndex++;
indexFinder = indexFinder.next;
}
result.append(randomIndex);
}
result.append("]");
curr = curr.next;
}
result.append("]");
return result.toString();
}
}