标签:leetcode 单链表 hashtable unordered_map queue
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.
Hash Table Linked Listthinking:
(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
标签:leetcode 单链表 hashtable unordered_map queue
原文地址:http://blog.csdn.net/hustyangju/article/details/45390539