[leetcode]Copy List with Random Pointer

这道题目以前见过,所以想了一下就想出来了http://www.cnblogs.com/lautsie/p/3259724.html。就是先修改指针维护一个从原先节点到新建节点的关系,最后再改回去。

实现过程中,一度忘记把node往前更新了。

public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null) return null;
        RandomListNode node = head;
        // copy node and change the structure
        while (node != null) {
            RandomListNode copyNode = new RandomListNode(node.label);
            copyNode.next = node.next;
            node.next = copyNode;
            node = copyNode.next;
        }        
        node = head;
        while (node != null) {
            node.next.random = node.random == null ? null : node.random.next;
            node = node.next.next;
        }
        // re-build the structure
        node = head;
        RandomListNode copyHead = head.next;
        while (node != null) {
            RandomListNode copyNode = node.next;
            node.next = copyNode.next;
            copyNode.next = node.next == null ? null : node.next.next;
            node = node.next;
        }
        return copyHead;
    }
}

  

posted @ 2013-10-09 17:24  阿牧遥  阅读(549)  评论(0编辑  收藏  举报