From fec24345f8c8c6f7fbc875f7046eab09f97dfbc7 Mon Sep 17 00:00:00 2001 From: Omooo <869759698@qq.com> Date: Tue, 2 Jun 2020 09:09:53 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E9=93=BE=E8=A1=A8=E7=9B=B8=E5=85=B3.m?= =?UTF-8?q?d?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blogs/Algorithm/剑指 Offer/链表相关.md | 53 ++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/blogs/Algorithm/剑指 Offer/链表相关.md b/blogs/Algorithm/剑指 Offer/链表相关.md index 034edb0..42a7196 100644 --- a/blogs/Algorithm/剑指 Offer/链表相关.md +++ b/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 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; + } +} +``` +