/* 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 pHead; } //定义一个指针,指向头结点 RandomListNode currentNode=pHead; //1、复制链表 while(currentNode!=null){ //创建源节点相同的复制结点 RandomListNode copyNode=new RandomListNode(currentNode.label); RandomListNode nextNode=currentNode.next; copyNode.next=nextNode; currentNode.next=copyNode; currentNode=nextNode; } //2、复制链表的复杂指针 //定义一个指针,指向头结点 currentNode=pHead; while(currentNode!=null){ //此处需要判断当前结点的任意指针是否为空 currentNode.next.random=currentNode.random==null?null:currentNode.random.next; currentNode=currentNode.next.next; } //3、将复制到链表与原来的链表拆开 //定义一个指针指向复制链表的头结点 currentNode=pHead; RandomListNode head=pHead.next; while(currentNode!=null){ RandomListNode currentNodeOfCopy=currentNode.next; currentNode.next=currentNodeOfCopy.next; //此处需要判断复制的结点是否是最后一个结点 currentNodeOfCopy.next=currentNodeOfCopy.next==null?null:currentNode.next.next; currentNode=currentNode.next; } return head; } }