思路: *1、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面; *2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next; *3、拆分链表,将链表拆分为原链表和复制后的链表
/* 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) { //1、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面; if(pHead==null) {return null;} RandomListNode c=pHead; //指针指向当前节点 while(c!=null) { RandomListNode clone=new RandomListNode(c.label); clone.next=c.next; clone.random=null; c.next=clone; c=clone.next; } //2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next; c=pHead; while(c!=null) { RandomListNode clone=c.next; if(c.random!=null) { clone.random=c.random.next; } c=clone.next; } //3拆分链表,将链表拆分为原链表和复制后的链表 c=pHead; RandomListNode cloneHead=pHead.next; while(c!=null) { RandomListNode clone=c.next; c.next=clone.next; if(clone.next==null) clone.next=null; else {clone.next=c.next.next;} c=c.next; } return cloneHead; } }
转载于:https://www.cnblogs.com/kexiblog/p/11131082.html