LeetCode--138. Copy List with Random Pointer

题目链接:https://leetcode.com/problems/copy-list-with-random-pointer/

题目要求一个链表的硬拷贝,这个链表的节点与传统节点不一样,每个节点成员变量有两个后驱节点的引用变量,一个是顺序结构的后驱节点引用,另一个是链表中随机选择的节点引用,这个似曾相识呀,就是图的硬拷贝,本题中的特殊链表就是图的一种特例呀,DFS和BFS都可以轻松搞定的,详细解释可以参考https://blog.csdn.net/To_be_to_thought/article/details/85344694,而本题也不用详细解释了,上代码:

public class Solution {
    HashMap<Integer,RandomListNode> map=new HashMap<Integer,RandomListNode>();
    
    public RandomListNode copyRandomList(RandomListNode head) {
        
        if(head==null)
            return null;
        if(map.containsKey(head.label))
            return map.get(head.label);
        
        RandomListNode ret=new RandomListNode(head.label);
        map.put(head.label,ret);
        ret.next=copyRandomList(head.next);
        ret.random=copyRandomList(head.random);
        return ret;
    }
}

效率一般!!!

猜你喜欢

转载自blog.csdn.net/To_be_to_thought/article/details/85530497