题目描述:
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.
深度复制,就所有的节点另外开辟空间咯。如果是一个一个遍历,然后寻找下一个random指针,这样时间复杂度是O(n*n),超时。
假设原始链表如下,细线表示next指针,粗线表示random指针,没有画出的指针均指向NULL:
我们在构建新链表的节点时,保存原始链表的next指针映射关系,并把指针做如下变化(蓝色为原始链表节点,紫红色为新链表节点):
然后在上图的基础上进行如下两步
1、构建新链表的random指针:比如new1->random = new1->random->random->next, new2->random = NULL, new3-random = NULL, new4->random = new4->random->random->next
2、恢复原始链表:根据最开始保存的原始链表next指针映射关系恢复原始链表
该算法时间空间复杂度均为O(N)
代码如下:
public RandomListNode copyRandomList(RandomListNode head) {
if(head==null)
return null;
RandomListNode headpre=new RandomListNode(-1);
RandomListNode resultpre=new RandomListNode(-1);
headpre.next=head;
RandomListNode pold=head,poldpre=headpre,pnewpre=resultpre;
Map<RandomListNode, RandomListNode> map=new HashMap<RandomListNode, RandomListNode>();
while(pold!=null){
map.put(poldpre, pold);
RandomListNode pnew =new RandomListNode(pold.label);
poldpre=pold;
pold=pold.next;
pnew.random=poldpre;
poldpre.next=pnew;
pnewpre.next=pnew;
pnewpre=pnew;
}
RandomListNode result=resultpre.next;
RandomListNode cur=result;
while(cur!=null){
if(cur.random.random==null)
cur.random=null;
else
cur.random=cur.random.random.next;
cur=cur.next;
}
pold=headpre;
for(int i=0;i<map.size();i++){
pold.next=map.get(pold);
pold=pold.next;
}
pold.next=null;
return result;
}
在这里要注意当恢复原来链表时,最后一个节点不能弄错了。最开始我是用的这个写法:
for(RandomListNode key:map.keySet()){
key.next=map.get(key);
}
这样写原链表的最后一个节点会指向新链表的最后一个节点,这点要小心。
还有一种更巧妙的方法:
1、构建新节点random指针:new1->random = old1->random->next, new2-random = NULL, new3-random = NULL, new4->random = old4->random->next
2、恢复原始链表以及构建新链表:例如old1->next = old1->next->next, new1->next = new1->next->next
该算法时间复杂度O(N),空间复杂度O(1)
代码如下:
代码如下:
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null)
return head;
/*第一步:在OldList的每个节点后面都插入一个copyNode(拷贝链表的结点)*/
RandomListNode nowNode = head;
while (nowNode != null){
RandomListNode copyNode = new RandomListNode(nowNode.label);
copyNode.random = nowNode.random;
copyNode.next = nowNode.next;
nowNode.next = copyNode;
nowNode = nowNode.next.next;
}
/*第二步:确定NewList的每个节点,真正关联到的Random结点是哪个,
* 因为第一步已经把所有NewList上的结点都建立了*/
nowNode = head;
while (nowNode != null){
if (nowNode.random != null){
nowNode.next.random = nowNode.random.next;
}
nowNode = nowNode.next.next;
}
/*第三步:还原OldList的next为一开始的next结点
* 并拼接NewList的next到它真正所应该关联的next结点
* 即:保持老链表OldList不变,拼接新链表NewList!
* */
RandomListNode pHead = new RandomListNode(0);
pHead.next = head;
RandomListNode newlist = pHead;
nowNode = head;
while (nowNode != null){
pHead.next = nowNode.next;
nowNode.next = pHead.next.next;
pHead = pHead.next;
nowNode = nowNode.next;
}
return newlist.next;
}