码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Copy List with Random Pointer

时间:2015-05-16 16:35:40      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:leetcode   hashmap   

题意:这个题目也是个蛮有意思的题目,就是对一个有随机指针的链表进行深拷贝,
思路:简单地来说就是递归拷贝,然后呢防止重复拷贝,所以凡是拷贝过得内存地址都得记录下来
代码:


    Map<RandomListNode, RandomListNode> m = new HashMap<RandomListNode, RandomListNode>();
    //保存已经copy的部分

    public RandomListNode copyRandomList(RandomListNode head) {
        RandomListNode rList = null;
        if(head == null) return rList;
        else {
            rList = new RandomListNode(head.label);
            m.put(head, rList);
            if(m.get(head.next) != null){
                rList.next = m.get(head.next);
            }else
                rList.next = copyRandomList(head.next);
            if(m.get(head.random) != null) {
                rList.random = m.get(head.random);
            }else
                rList.random = copyRandomList(head.random);
        }

        return rList;
    }


[LeetCode]Copy List with Random Pointer

标签:leetcode   hashmap   

原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/45768711

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!