leetcode || 138、Copy List with Random Pointer

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];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值