LeetCode-138 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.

Return a deep copy of the list.

 

思路:

 

 

代码如下:

public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null) 
            return null;
        
        RandomListNode r = head;
        while(r != null) {
            RandomListNode tmp = r.next;
            r.next = new RandomListNode(r.label);
            r.next.next = tmp;
            r = r.next.next;
        }
        
        r = head;
        RandomListNode nr;
        while(r != null) {
            nr = r.next;
            if(r.random == null)
                nr.random = null;
            else
                nr.random = r.random.next;
            r = nr.next;
        }
        
        r = head;
        nr = r.next;
        RandomListNode result = nr;
        while(r != null) {
            r.next = nr.next;
            if(nr.next != null)
                nr.next = nr.next.next;
            r = r.next;
            nr = nr.next;
        }
        return result;
    }

 

posted on 2015-02-25 18:32  linxiong1991  阅读(358)  评论(0)    收藏  举报

导航