题目
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路
这道题的难点就在于链表节点的特殊指针的复制,因为特殊指针是指向随机节点的,所以没法边复制节点边获取特殊指针。因此比较简便的方法是在原链表的每个节点后面增加他的复制节点:
如:原链表为:1->2->3->4,增加复制节点后:1->1->2->2->3->3->4->-4。
这样做的好处是,复制链表的每个节点的特殊指针都是原链表对应节点的特殊指针的下一位,这样就解决了特殊指针的复制问题。最后在将修改后原链表拆分成两个链表:原版的链表和复制链表。
代码
/*
public class RandomListNode
{
public int label;
public RandomListNode next, random;
public RandomListNode (int x)
{
this.label = x;
}
}*/
class Solution
{
public RandomListNode Clone(RandomListNode pHead)
{
// write code here
if(pHead==null)
return null;
RandomListNode head;
RandomListNode headNode;
RandomListNode node=pHead;
RandomListNode node2;
while(node!=null)//为原链表增加复制节点
{
node2=new RandomListNode(node.label);
node2.random=node.random;
node2.next=node.next;
node.next=node2;
node=node2.next;
}
node=pHead;
while(node!=null)//完成复制的节点的特殊指针赋值
{
node2=node.next;
if(node2.random!=null)
node2.random=node2.random.next;
node=node2.next;
}
node=pHead.next;
head=node;//复制链表的头结点
headNode=head;
pHead.next=node.next;//去除前面为pHead复制的重复节点
pHead=pHead.next;
while(node.next!=null)//拆分链表
{
node=node.next.next;
headNode.next=node;
headNode = headNode.next;
pHead.next=node.next;//去除前面为pHead复制的重复节点
pHead=pHead.next;
}
return head;
}
}