Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit121ca50

Browse files
authored
Refactored Copy List with Random Pointer.java
1 parentd54d295 commit121ca50

File tree

1 file changed

+31
-26
lines changed

1 file changed

+31
-26
lines changed
Lines changed: 31 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,33 @@
1-
/**
2-
* Definition for singly-linked list with a random pointer.
3-
* class RandomListNode {
4-
* int label;
5-
* RandomListNode next, random;
6-
* RandomListNode(int x) { this.label = x; }
7-
* };
8-
*/
9-
publicclassSolution {
10-
publicRandomListNodecopyRandomList(RandomListNodehead) {
11-
if (head ==null) {
12-
returnnull;
13-
}
14-
15-
RandomListNodeans =newRandomListNode(head.label);
16-
RandomListNodecurr =ans;
17-
18-
while (head !=null) {
19-
curr.next =head.next ==null ?null :newRandomListNode(head.next.label);
20-
curr.random =head.random ==null ?null :newRandomListNode(head.random.label);
21-
22-
curr =curr.next;
23-
head =head.next;
24-
}
25-
26-
returnans;
1+
/*
2+
// Definition for a Node.
3+
class Node {
4+
int val;
5+
Node next;
6+
Node random;
7+
8+
public Node(int val) {
9+
this.val = val;
10+
this.next = null;
11+
this.random = null;
2712
}
2813
}
14+
*/
15+
16+
classSolution {
17+
publicNodecopyRandomList(Nodehead) {
18+
Map<Node,Node>map =newHashMap<>();
19+
Nodecurr =head;
20+
while (curr !=null) {
21+
map.put(curr,newNode(curr.val));
22+
curr =curr.next;
23+
}
24+
curr =head;
25+
while (curr !=null) {
26+
Nodetemp =map.get(curr);
27+
temp.next =curr.next ==null ?null :map.get(curr.next);
28+
temp.random =curr.random ==null ?null :map.get(curr.random);
29+
curr =curr.next;
30+
}
31+
returnmap.get(head);
32+
}
33+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp