Update 链表相关.md

master
Omooo 5 years ago
parent 9f2af8ed20
commit fec24345f8
  1. 53
      blogs/Algorithm/剑指 Offer/链表相关.md

@ -169,3 +169,56 @@ class Solution {
}
```
[35. 复杂链表的复制](https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/)
```java
class Solution {
public Node copyRandomList(Node head) {
// 存原节点和拷贝节点的一个映射
Map<Node, Node> map = new HashMap<>();
Node temp = head;
while (temp != null) {
map.put(temp, new Node(temp.val));
temp = temp.next;
}
temp = head;
while (temp != null) {
// 将拷贝节点组织成一个链表
map.get(temp).random = map.get(temp.random);
map.get(temp).next = map.get(temp.next);
temp = temp.next;
}
return map.get(head);
}
}
```
```java
class Solution {
public Node copyRandomList(Node head) {
// 将拷贝节点放在原节点后面,比如 1->2 变成 1->1'->2->2'
for (Node node = head, copy = null; node != null; node = node.next.next) {
copy = new Node(node.val);
copy.next = node.next;
node.next = copy;
}
// 把拷贝节点的 random 指针安排上
for (Node node = head; node != null; node = node.next.next) {
if (node.random != null) {
node.next.random = node.random.next;
}
}
Node newHead = head.next;
Node node = head;
Node temp = null;
// 分离原节点和拷贝节点
while (node != null && node.next != null) {
temp = node.next;
node.next = temp.next;
node = temp;
}
return newHead;
}
}
```

Loading…
Cancel
Save