思路:
两次遍历原链表,,第一次拷贝除随机指针外的内容,第二次拷贝随机指针。
在第一次遍历的过程中要记录旧结点到新节点的映射关系,在拷贝随机指针的时候需要根据映射关系来为随机指针赋值。
/* public class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null; RandomListNode(int label) { this.label = label; } } */ import java.util.*; public class Solution { public RandomListNode Clone(RandomListNode pHead) { if(pHead == null) return null; if(pHead.next == null) return new RandomListNode(pHead.label); RandomListNode newHead = new RandomListNode(pHead.label); // 创建一个新的头结点 RandomListNode cur = pHead.next; RandomListNode tail = newHead; HashMap<RandomListNode,RandomListNode> map = new HashMap<>(); map.put(pHead,newHead); while(cur != null){ tail.next = new RandomListNode(cur.label); map.put(cur,tail.next); tail = tail.next; cur = cur.next; } // 进行随机指针的复制 tail = newHead; cur = pHead; while(cur != null){ tail.random = map.get(cur.random); cur = cur.next; tail = tail.next; } // 返回结果 return newHead; } }