Copy List with Random Pointer

题目地址:
https://leetcode.com/problems/copy-list-with-random-pointer/#/description

题目:
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.
解题思路:
这道题需要用到map这个辅助结构,将node按照顺序loop一遍,然后new一个数值一样的node存到map的value里面,然后把map再loop一遍。

代码:



public RandomListNode copyRandomList(RandomListNode head) {
    if(head == null){
        return null;
    }
    HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
    RandomListNode curr = head;
    while(curr != null){
        map.put(curr, new RandomListNode(curr.label));
        curr = curr.next;
    }
    for(Map.Entry<RandomListNode, RandomListNode> entry : map.entrySet()){
        RandomListNode newNode = entry.getValue();
        newNode.next = map.get(entry.getKey().next);
        newNode.random = map.get(entry.getKey().random);
    }
    return map.get(head);
}

Comments

Popular Posts