-
Notifications
You must be signed in to change notification settings - Fork 1
/
138.复制带随机指针的链表.java
84 lines (79 loc) · 1.96 KB
/
138.复制带随机指针的链表.java
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
* @lc app=leetcode.cn id=138 lang=java
*
* [138] 复制带随机指针的链表
*
* https://leetcode-cn.com/problems/copy-list-with-random-pointer/description/
*
* algorithms
* Medium (34.57%)
* Likes: 137
* Dislikes: 0
* Total Accepted: 12.4K
* Total Submissions: 32.7K
* Testcase Example: '{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}'
*
* 给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
*
* 要求返回这个链表的深拷贝。
*
*
*
* 示例:
*
*
*
* 输入:
*
* {"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}
*
* 解释:
* 节点 1 的值是 1,它的下一个指针和随机指针都指向节点 2 。
* 节点 2 的值是 2,它的下一个指针指向 null,随机指针指向它自己。
*
*
*
*
* 提示:
*
*
* 你必须返回给定头的拷贝作为对克隆列表的引用。
*
*
*/
// @lc code=start
/*
// Definition for a Node.
class Node {
public int val;
public Node next;
public Node random;
public Node() {}
public Node(int _val,Node _next,Node _random) {
val = _val;
next = _next;
random = _random;
}
};
*/
class Solution {
public Node copyRandomList(Node head) {
Map<Node, Node> readed = new HashMap<>();
return copyRandomList(head, readed);
}
private Node copyRandomList(Node node, Map<Node, Node> readed) {
if (node == null) {
return null;
}
if (readed.containsKey(node)) {
return readed.get(node);
}
Node cloned = new Node();
readed.put(node, cloned);
cloned.val = node.val;
cloned.next = copyRandomList(node.next, readed);
cloned.random = copyRandomList(node.random, readed);
return cloned;
}
}
// @lc code=end