[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;

    }

}

  

你可能感兴趣的:(LeetCode)