题目
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路
题目有一个非常狠的限制条件那就是,不能使用引用拷贝。那么我们就只能自己先创建一个链表对其进行操作。具体操作如下:
- 复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面。
- 重新遍历链表,复制老结点的随机指针给新结点,如
A1.random = A.random.next;
- 拆分链表,将链表拆分为原链表和复制后的链表
AC代码
/*
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 answer = pHead;
// 1.复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面。
while(answer != null){
RandomListNode clone = new RandomListNode(answer.label);
clone.next = answer.next;
//clone.random = answer.random;
answer.next = clone;
answer = clone.next;
}
// 2.重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
answer = pHead;
while(answer!=null){
if(answer.random!=null) answer.next.random = answer.random.next;
answer = answer.next.next;
}
// 3.拆分链表,将链表拆分为原链表和复制后的链表
answer = pHead;
RandomListNode pCloneHead = pHead.next;
while(answer != null){
RandomListNode cloneNode = answer.next;
answer.next = answer.next.next;
if(cloneNode.next != null)
cloneNode.next = cloneNode.next.next;
answer = answer.next;
}
return pCloneHead;
}
}