Open larscheng opened 3 months ago
方法二:拼接+拆分
O(n)/O(1)
// 哈希表
public Node copyRandomList(Node head) {
Map<Node, Node> map = new HashMap<>();
Node cur = head;
//收集 老节点-新节点 map
while (cur != null) {
map.put(cur, new Node(cur.val));
cur = cur.next;
}
Node oldCur = head;
while (oldCur != null) {
Node newNode = map.get(oldCur);
newNode.next = map.get(oldCur.next);
newNode.random = map.get(oldCur.random);
oldCur = oldCur.next;
}
return map.get(head);
}
```java
//拼接+拆分
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
Node cur = head;
while (cur != null) {
//相邻复制
Node temp = new Node(cur.val);
temp.next = cur.next;
cur.next = temp;
cur = temp.next;
}
cur = head;
while (cur != null) {
//给复制节点设置random
if (cur.random != null) {
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
cur = head.next;
Node pre = head;
Node res = head.next;
while (cur.next != null) {
pre.next = pre.next.next;
cur.next = cur.next.next;
pre = pre.next;
cur = cur.next;
}
pre.next = null;
return res;
}
138. 随机链表的复制