首页 > 代码库 > LeetCode "Copy List with Random Pointer"
LeetCode "Copy List with Random Pointer"
Two passes: all pointer linking info will be recorded in 1st pass - to hashmap; 2nd pass recover the pointer relationship from hashmap. 1A!
class Solution {public: RandomListNode *copyRandomList(RandomListNode *head) { if (!head) return NULL; vector<RandomListNode *> vec; unordered_map<RandomListNode *, unsigned> ptrMap; // 1st pass RandomListNode *p = head; unsigned i = 0; while (p) { RandomListNode *pCurr = new RandomListNode(p->label); pCurr->random = p->random; pCurr->next = p->next; vec.push_back(pCurr); ptrMap.insert(make_pair(p, i ++)); p = p->next; } // 2nd pass for (int i = 0; i < vec.size(); i++) { RandomListNode *pCurr = vec[i]; if (pCurr->next) pCurr->next = vec[ptrMap[pCurr->next]]; if (pCurr->random) pCurr->random = vec[ptrMap[pCurr->random]]; } return vec[0]; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。