1. 题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
2. 解题思路
(1)可以考虑开始的时候在每个节点的后面插入复制的节点,然后对对复制节点的 random 链接进行赋值,最后拆分链表。
(2)先复制链表的next节点,将复制后的节点接在原节点后,然后复制其它的节点。这个思路简单点。
3.代码实现
(1)
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if (pHead == null)
return null;
//复制next结点
RandomListNode node = pHead;
while (node != null){
RandomListNode newNode = new RandomListNode(node.label);
newNode.next = node.next;
node.next = newNode;
node = newNode.next;
}
//连接random结点
node = pHead;
while (node != null){
RandomListNode newNode = node.next;
if (node.random != null){
newNode.random = node.random.next;
}
node = newNode.next;
}
//拆为两条链表
node = pHead;
RandomListNode clone = pHead.next;
while (node.next != null){
RandomListNode next = node.next;
node.next = next.next;
node = next;
}
return clone;
}
}
(2)
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if (pHead == null)
return null;
RandomListNode head = new RandomListNode(pHead.label);
RandomListNode temp = head;
while (pHead.next != null){
temp.next = new RandomListNode(pHead.next.label);
if (pHead.random != null){
temp.random = new RandomListNode(pHead.random.label);
}
pHead = pHead.next;
temp = temp.next;
}
return head;
}
}