输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
解析:见代码
代码:
①用map保存复制的新的节点
/*
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)
{
HashMap<RandomListNode,RandomListNode> map = new HashMap<>();
RandomListNode p = pHead;
//第一次遍历,保存新的节点;相当于复制
while(p != null){
RandomListNode newNode = new RandomListNode(p.label);
map.put(p,newNode);
p = p.next;
}
p = pHead;
//第二次遍历,将原映射复制到新的节点中
while(p != null){
RandomListNode node = map.get(p);
node.next = (p.next == null)? null:map.get(p.next);
node.random = (p.random == null) ? null:map.get(p.random);
p = p.next;
}
return map.get(pHead);
}
}
*********************************************************************************************************************
②在原表中复制
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if(pHead == null){
return null;
}
RandomListNode currentNode = pHead;
//复制每个节点,将复制节点插入到原节点的后边
while(currentNode != null){
//复制A节点
RandomListNode cloneNode = new RandomListNode(currentNode.label);
//获得B节点
RandomListNode nextNode = currentNode.next;
//A节点指向复制节点
currentNode.next = cloneNode;
//复制节点指向B节点
cloneNode.next = nextNode;
//由A节点移到B节点
currentNode = nextNode;
}
//复制映射关系
currentNode = pHead;
while(currentNode != null){
currentNode.next.random = currentNode.random == null? null:currentNode.random.next;
currentNode = currentNode.next.next;
}
//拆分,拆除复制结果
currentNode = pHead;
RandomListNode pCloneNode = pHead.next;
while(currentNode != null){
//复制节点
RandomListNode cloneNode = currentNode.next;
//更新原节点的next
currentNode.next = cloneNode.next;
//更新复制节点next
cloneNode.next = cloneNode.next == null? null : cloneNode.next.next;
//更新原节点指针
currentNode = currentNode.next;
}
return pCloneNode;
}
}