-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path138.随机链表的复制.java
84 lines (70 loc) · 1.86 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] 随机链表的复制
*/
// @lc code=start
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
import java.util.HashMap;
import java.util.Map;
class Solution {
Map<Node, Node> old2new = new HashMap<>();
public Node copyRandomList(Node head) {
// return copyRandomListRecursion(head);
return copyRandomListIteration(head);
}
// hashtable
Node copyRandomListRecursion(Node head) {
if (head == null) {
return null;
}
if (old2new.get(head) == null) {
Node newHead = new Node(head.val);
old2new.put(head, newHead);
newHead.next = copyRandomListRecursion(head.next);
newHead.random = copyRandomListRecursion(head.random);
}
return old2new.get(head);
}
Node copyRandomListIteration(Node head) {
if (head == null) return null;
// create new nodes
Node node = head;
while (node != null) {
Node newNode = new Node(node.val);
newNode.next = node.next;
node.next = newNode;
node = newNode.next;
}
// link random
node = head;
while (node != null) {
Node next = node.next;
next.random = node.random == null ? null : node.random.next;
node = next.next;
}
// split new list
node = head;
head = head.next;
while (node != null) {
Node next = node.next;
node.next = node.next.next;
next.next = next.next == null ? null : next.next.next;
node = node.next;
}
return head;
}
}
// @lc code=end