首页 > 其他 > 详细

leetcode || 138、Copy List with Random Pointer

时间:2015-04-30 10:43:03      阅读:186      评论:0      收藏:0      [点我收藏+]

problem:

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.

Hide Tags
 Hash Table Linked List
题意:copy一个单链表,单链表的节点多了一个指针,随机指向一个节点或者空

thinking:

(1)这道题其实蛮简单,诀窍在于hash table的应用。

(2)使用 unordered_map<RandomListNode *, RandomListNode *> record;底层是借助hash table实现的,访问效率高。

这种存储新旧节点指针的方法在图的copy中也用到过,效率奇高!

(3)先遍历链表,将新旧节点指针存入hash table,先不管next指针和random指针。

(4)再遍历hash table,找到旧节点next和random的指向,跟新新节点的next指针和random指针。

注意先调用count()或者find()判断key值是否存在

code:

class Solution {
private:
    unordered_map<RandomListNode *, RandomListNode *> record;
    queue<RandomListNode *> _queue;
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if(head==NULL)
            return NULL;
        _queue.push(head);
        while(!_queue.empty())
        {
            RandomListNode *tmp=_queue.front();
            _queue.pop();
            if(tmp->next!=NULL)
                _queue.push(tmp->next);
            RandomListNode *tmp2= new RandomListNode(tmp->label);
            record.insert(make_pair(tmp,tmp2));
        }
        for(unordered_map<RandomListNode *,RandomListNode *>::iterator it=record.begin();it!=record.end();++it)
        {
            RandomListNode *tmp3=it->first;
            RandomListNode *tmp4=it->second;
            if(record.count(tmp3->next)!=0)
                tmp4->next=record[tmp3->next];
            else
                tmp4->next=NULL;

            if(record.count(tmp3->random)!=0)
                tmp4->random=record[tmp3->random];
            else
                tmp4->random=NULL;
            
        }
        return record[head];
    }
};


leetcode || 138、Copy List with Random Pointer

原文:http://blog.csdn.net/hustyangju/article/details/45390539

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!