题解 | #复杂链表的复制#
思路:
- 通过递归拷贝所有next节点
- 在拷贝过程中将原节点和拷贝节点的对应关系存入Map
- 在递归返回的过程中,通过Map拷贝random节点
代码:
public class Solution {
HashMap<RandomListNode, RandomListNode> haved = new HashMap<>();
public RandomListNode Clone(RandomListNode pHead) {
if (pHead != null) {
RandomListNode copyNode = new RandomListNode(pHead.label);
haved.put(pHead, copyNode);
copyNode.next = Clone(pHead.next);
copyNode.random = haved.get(pHead.random);
return copyNode;
}
return null;
}
}