A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Subscribe to see which companies asked this question
题目分析:深度复制链表,既要复制next,又要复制random,next好复制,random要怎么处理呢,考虑到我们只知道链表的下一个节点是什么。那我们就在链表之后插入复制的节点,之后再进行调整。
可以分为3步:
1.在每个节点后插入复制的节点
2.复制random
3. 分离两条链表
具体代码如下:
public RandomListNode copyRandomList(RandomListNode head) {
if(head==null) return null;
RandomListNode newhead=null;
RandomListNode now=head;
// 第一步在当前节点之后,插入赋值节点
while(now!=null)
{
RandomListNode copy=new RandomListNode(now.label);
copy.next=now.next;
now.next=copy;
now=now.next.next;
}
//第二步,拷贝RandomNode
now=head;
while(now!=null)
{
if(now.random!=null)
now.next.random=now.random.next;
now=now.next.next;
}
//第三步,还原两条链表
now=head;
newhead=now.next;
RandomListNode p=newhead;
while(now!=null)
{
now.next=now.next.next;
//当之后没有节点时,p.next=null。需要进行非空判断
if(p.next!=null)
p.next=p.next.next;
now=now.next;
p=p.next;
}
return newhead;
}