/**
* 问题复杂链表的复制
* 描述:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
* 知识点:散列 很喜欢的一道题
*
* @param pHead
* @return
*/
public RandomListNode Clone(RandomListNode pHead) {
if (pHead == null) return null;
HashMap<RandomListNode, RandomListNode> hash = new HashMap<>();
HashMap<RandomListNode, RandomListNode> hash2 = new HashMap<>();
RandomListNode head = new RandomListNode(-1);
RandomListNode temp = head;
while (pHead != null) {
RandomListNode t = new RandomListNode(pHead.label);
hash.put(pHead, t);
hash2.put(t, pHead);
temp.next = t;
temp = t;
pHead = pHead.next;
}
RandomListNode temp2 = head.next;
while (temp2 != null) {
temp2.random = hash.get(hash2.get(temp2).random);
temp2 = temp2.next;
}
return head.next;
}
问题复杂链表的复制
最新推荐文章于 2021-06-04 00:38:45 发布