思路之一:
1、Map<Integer,RandomListNode> 存储新链表的节点
2、遍历旧链表,遍历的同时深度克隆每一个节点,并建立关系
import java.util.*; public class Solution { public RandomListNode Clone(RandomListNode pHead){ if(pHead==null) return null; RandomListNode newNode = null; RandomListNode retHead = null; Map<Integer,RandomListNode> nodeMap = new HashMap<>(); boolean isHead = true; while(pHead!=null){ //克隆当前节点 newNode = cloneNode(pHead.label,nodeMap); if(pHead.random!=null){ //克隆random指针节点 newNode.random = cloneNode(pHead.random.label,nodeMap); } if(pHead.next!=null){ //克隆next指针节点 newNode.next = cloneNode(pHead.next.label,nodeMap); } if(isHead){ //记录下头节点,返回结果用 retHead = newNode; isHead = false; } pHead = pHead.next; newNode = newNode.next; } return retHead; } //克隆节点 public RandomListNode cloneNode(int label,Map<Integer,RandomListNode> map){ RandomListNode node = map.get(label); if(node==null){ node = new RandomListNode(label); map.put(label,node); } return node; } }