Friday, November 13, 2015

[leetcode] Copy List with Random Pointer

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

No comments:

Post a Comment