题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路1:哈希
产生O(n)的空间,时间也是)(n),以空间换时间.
import java.util.HashMap;
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if(pHead==null)return pHead;
RandomListNode head=new RandomListNode(pHead.label);
if(pHead.next==null){
head.random=(pHead.random==null?null:head);
return head;
}
HashMap<RandomListNode,RandomListNode> hm=new HashMap<>();
hm.put(pHead,head);
RandomListNode t_pHead=pHead,t_head=head;
while(t_pHead.next!=null){
RandomListNode next=new RandomListNode(t_pHead.next.label);
t_head.next=next;
t_pHead=t_pHead.next;
t_head=t_head.next;
hm.put(t_pHead,t_head);
}
t_pHead=pHead;
t_head=head;
while(t_pHead!=null){
t_head.random=(t_pHead.random==null?null:hm.get(t_pHead.random));
t_pHead=t_pHead.next;
t_head=t_head.next;
}
return head;
}
}
思路2:
不使用哈希表来保存对应关系,而只用有限的几个变量完成所有的功能.
1、复制链表
2、新旧链表分叉连接(旧1->新1->旧1->新1->…)
3、新链表的random,是旧链表对应结点的random的下一结点
4、断开链表得新、旧两个链表
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if(pHead==null)return pHead;
RandomListNode t_pHead=pHead;
//复制结点,同时将其串接进旧链表
while(t_pHead!=null){
RandomListNode now=new RandomListNode(t_pHead.label);
now.next=t_pHead.next;
t_pHead.next=now;
t_pHead=t_pHead.next.next;
}
t_pHead=pHead;
//根据旧链表的random结点,获知新链表的random结点
while(t_pHead!=null){
t_pHead.next.random=(t_pHead.random==null?null:t_pHead.random.next);//注意点
t_pHead=t_pHead.next.next;
}
RandomListNode head=pHead.next,t_head=head;
t_pHead=pHead;
//断开链表得新、旧链表
while(t_pHead.next.next!=null){ //注意点
t_pHead.next=t_head.next;
t_pHead=t_pHead.next;
t_head.next=t_pHead.next;
t_head=t_head.next;
}
t_pHead.next=null;
return head;
}
}