题目:
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof
思路:
拿到这道题,相较于普通的链表复制,这道题的麻烦点在random指向的节点可能已经存在,也可能没创建,或者为null。
暴力解法就是先复制节点的值和next,再一个个比对复制random,显然时间复杂度O(n2)不是好的解题思路。
这里我们采用哈希表来解题(一方面是containsKey方法方便我们快速判断节点是否已经存在,另一方面,我们通过key来存储原来链表的节点,并使原节点和复制的节点一一对应,可以起到区分复制的节点的作用)
代码:
import org.w3c.dom.Node;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Node1 node1 = new Node1(7);
Node1 node2 = new Node1(13);
Node1 node3 = new Node1(11);
Node1 node4 = new Node1(10);
Node1 node5 = new Node1(1);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = null;
node1.random = null;
node2.random = node1;
node3.random = node5;
node4.random = node3;
node5.random = node1;
Node1 temp = node1;
while (temp != null) {
System.out.println(temp);
temp = temp.next;
}
Solution solution = new Solution();
System.out.println("-----------------------------");
temp = solution.copyRandomList(node1);
while (temp != null) {
System.out.println(temp);
temp = temp.next;
}
}
}
class Solution {
public Node1 copyRandomList(Node1 head) {
if (head == null) {
return null;
}
Map<Node1, Node1> hashMap = new HashMap<>();
Node1 temp = head;
Node1 newTemp = new Node1(temp.val);
hashMap.put(temp, newTemp);
while (temp != null) {
if (temp.next == null) {
newTemp.next = null;
} else if (!hashMap.containsKey(temp.next)) {
newTemp.next = new Node1(temp.next.val);
hashMap.put(temp.next, newTemp.next);
} else {
newTemp.next = hashMap.get(temp.next);
}
if (temp.random == null) {
newTemp.random = null;
} else if (!hashMap.containsKey(temp.random)) {
newTemp.random = new Node1(temp.random.val);
hashMap.put(temp.random, newTemp.random);
} else {
newTemp.random = hashMap.get(temp.random);
}
temp = temp.next;
newTemp = newTemp.next;
}
return hashMap.get(head);
}
}
class Node1 {
int val;
Node1 next;
Node1 random;
public Node1(int val) {
this.val = val;
this.next = null;
this.random = null;
}
public String toString() {
return "[val=" + val + ",next=" + (next == null ? "null" : next.val) + ",random=" + (random == null ? "null" : random.val) + "]";
}
}
结果: