题目描述
现在有一个这样的链表:链表的每一个节点都附加了一个随机指针,随机指针可能指向链表中的任意一个节点或者指向空。
请对这个链表进行深拷贝。
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.
分析
因为这个链表的随机指针有可能指向链表中的任意结点,意味着一个位置靠前的结点的随机指针有可能指向了靠后的链表结点,所以在拷贝的时候就不可以直接从前往后去拷贝结点和随机指针(随即指针不能指向不存在的结点,因此时后面的结点还没进行创建)
因此使用了一个非常巧妙的方法,步骤如下:
1.在原链表上的每一个结点后都插入一个相同的结点,相当于这个链表中每一个结点都会重复相连地出现两次;
2.接下来修改拷贝结点的随机指针的指向,使其指向其“母”结点的随机指针指向的结点的下一个结点(即与之相应的拷贝结点)
3.最后分离出拷贝的链表即可。
时间复杂度
O(n)
代码
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null)return null;
//在链表的每一个结点后都插入相同的结点
RandomListNode p = head;
while(p != null){
RandomListNode copy = new RandomListNode(p.label);
copy.next = p.next;
p.next = copy;
p = copy.next;
}
//加入随机指针
p = head;
RandomListNode copy = head.next;
while(p != null){
if(p.random != null)copy.random = p.random.next;
else copy.random = null;
p = copy.next;
if(p!=null)
copy = p.next;
}
//分离出拷贝的链表
RandomListNode q = head.next;
copy = q;
while(q != null && q.next != null){//注意结束循环条件,我又卡了很久
RandomListNode next = q.next.next;
q.next = next;
q = q.next;
}
return copy;
}
}