题解 | #复杂链表的复制#
复杂链表的复制
http://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba
!注意区分引用操作和实体操作
// public class RandomListNode { // int label; // RandomListNode next = null; // RandomListNode random = null; // RandomListNode(int label) { // this.label = label; // } // RandomListNode(){} // } public class Solution { //先实例化一个头 static RandomListNode result=new RandomListNode(1); public RandomListNode Clone(RandomListNode pHead) { if(pHead==null){ return null; } fun(pHead,result); return result; } public void fun(RandomListNode pHead,RandomListNode res){ //pHead指向待复制节点,res指向当前空间 //复制节点值 if(pHead!=null) { res.label = pHead.label; } //建立random节点并复制 if(pHead.random!=null) { res.random = new RandomListNode(pHead.random.label); } //建立并复制下一个节点,并将待处理指针指向下一个节点 if(pHead.next!=null){ res.next=new RandomListNode(pHead.next.label); res=res.next; pHead=pHead.next; fun(pHead,res); } } }