25 复杂链表的复制

题目描述

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
 
 1 public class Solution {
 2     public RandomListNode Clone(RandomListNode head)
 3     {
 4         if(head==null) return null;
 5         //copy
 6         for(RandomListNode cur = head;cur!=null;cur=cur.next.next){
 7             RandomListNode copy= new RandomListNode(cur.label);
 8             copy.next = cur.next;
 9             cur.next = copy;
10         }
11        // copy random
12       for(RandomListNode cur = head;cur!=null;cur=cur.next.next)
13             if(cur.random!=null) //如果存在随机指针 
14                 cur.next.random=cur.random.next;
15         //split
16         RandomListNode  cur = head;
17         RandomListNode copy_cur = head.next;
18         RandomListNode copy_head =head.next; 
19         while(cur!=null){
20             cur.next = cur.next.next;
21             if(copy_cur.next!=null) copy_cur.next = copy_cur.next.next;
22             copy_cur = copy_cur.next;
23             cur = cur.next;
24 
25         }
26         
27         return  copy_head;        
28     }
29 }

 

posted @ 2017-12-13 21:31  乐乐章  阅读(124)  评论(0编辑  收藏  举报