Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

 

 1 public class Solution {
 2     public RandomListNode copyRandomList(RandomListNode head) {
 3         if(head==null) return head;
 4         //insert
 5         RandomListNode p = head;
 6         while(p!=null){
 7             RandomListNode temp = p.next;
 8             RandomListNode node = new RandomListNode(p.label);
 9             p.next = node;
10             node.next = temp;
11             p = temp;
12         }
13         //copy ran
14         p = head;
15         while(p!=null){
16             if(p.random!=null){
17                 p.next.random = p.random.next;
18             }
19             else{
20                 p.next.random = null;
21             }
22             p = p.next.next;
23         }
24         //divide
25         p = head;
26         RandomListNode head2 = p.next;
27         while(p!=null){
28             RandomListNode temp = p.next;
29             if(temp!=null)
30                 p.next = temp.next;
31             p = temp;
32         }
33         return head2;
34     }
35 }
View Code

 

 

 

 1 public class Solution {
 2     public RandomListNode copyRandomList(RandomListNode head) {
 3         //insert nodes
 4         RandomListNode cur = head;
 5         while(cur!=null){
 6             RandomListNode temp = new RandomListNode(cur.label);
 7             temp.next = cur.next;
 8             cur.next = temp;
 9             cur = temp.next;
10         }
11         //copy random pointers
12         cur = head;
13         while(cur!=null){
14             RandomListNode temp = cur.next;
15             if(cur.random!=null)
16                 temp.random = cur.random.next;
17             cur = temp.next;
18         }
19         cur = head;
20         RandomListNode newHead = head==null?null:head.next;
21         while(cur!=null){
22             RandomListNode temp = cur.next;
23             cur.next = temp.next;
24             if(temp.next!=null)
25                 temp.next = temp.next.next;
26             cur = cur.next;
27         }
28         return newHead;
29     }
30 }
View Code

 

posted @ 2014-02-22 13:04  krunning  阅读(143)  评论(0编辑  收藏  举报