138. Copy List with Random Pointer
来源:互联网 发布:nat123访问数据库很慢 编辑:程序博客网 时间:2024/06/06 19:09
这道题给出一个链表,链表每一个节点都有一个指针,指向链表中的任意一个节点或者null,要求复制这个链表。
每次复制一个节点,肯定要填上random指针,但是random指针怎么才能知道呢,如果在链表里一个一个找那肯定是不可能。为了不用一个一个的比较所有节点的label这样搜索,可以把原链表的每个节点到新链表里的相应节点的映射写在一个哈希表里,就不用搜索了。
所以这个题首先根据next指针把链表串起来,然后再遍历原链表,根据哈希表里的对应关系,把新链表的random指针都连好。
/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label; * RandomListNode *next, *random; * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */class Solution {public: RandomListNode *copyRandomList(RandomListNode *head) { if(!head) return NULL; RandomListNode* res = new RandomListNode(head->label); RandomListNode* node = res; RandomListNode* cur = head->next; unordered_map<RandomListNode*, RandomListNode*> m; m[head] = res; while(cur){ RandomListNode* tmp = new RandomListNode(cur->label); node->next = tmp; m[cur] = tmp; node = node->next; cur = cur->next; } node = res; cur = head; while(node){ node->random = m[cur->random]; node = node->next; cur = cur->next; } return res; }};
阅读全文
0 0
- 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- [Leetcode] 138. Copy List with Random Pointer
- 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- [leetcode] 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- 138. Copy List with Random Pointer
- leetcode.138. Copy List with Random Pointer
- 138. Copy List with Random Pointer
- LeetCode-138.Copy List with Random Pointer
- Leetcode 138. Copy List with Random Pointer
- [Leetcode]138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- 138. Copy List with Random Pointer
- [LeetCode] 138. Copy List with Random Pointer
- 7-1 畅通工程之局部最小花费问题
- static关键字总结
- android仿京东商城项目
- 内存管理(1)--动态分区分配策略
- mybatis(4)---优化配置文件中的配置
- 138. Copy List with Random Pointer
- 问面试官
- ArrayList既然继承自AbstractList抽象类,而AbstractList已经实现了List接口,那么ArrayList类为何还要再实现List接口呢?
- 泛型的经典例子
- arm linux RouterSploit
- 状态栏配置
- Andrew Ng 深度学习课程Deeplearning.ai 编程作业——deep Neural network for image classification(1-4.2)
- QT 构建时错误
- 2017-11-02