输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
/**
* Created by artsing on 2019/8/10.
*/
class RandomListNode{
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
public class Main {
public static void main(String[] args){
RandomListNode node0 = new RandomListNode(0);
RandomListNode node1 = new RandomListNode(1);
RandomListNode node2 = new RandomListNode(2);
RandomListNode node3 = new RandomListNode(3);
RandomListNode node4 = new RandomListNode(4);
node0.next=node1;
node0.random=node2;
node1.next=node2;
node1.random=node4;
node2.next=node3;
node3.next=node4;
Clone(node0);
}
public static RandomListNode Clone(RandomListNode pHead)
{
//先加一遍next节点
RandomListNode temp1 =pHead;
while(temp1!=null){
RandomListNode add = new RandomListNode(temp1.label);
add.next=temp1.next;
temp1.next=add;
temp1=add.next;
}
//再把random关联上
RandomListNode temp2 =pHead;
while(temp2!=null){
if(temp2.random!=null){
temp2.next.random=temp2.random.next;
}
}
//再把新加的节点连接起来
RandomListNode result= pHead.next;
RandomListNode temp3 =result;
while(temp3.next!=null){
temp3.next=temp3.next.next;
}
return result;
}
}