Copy List with Random Pointer
来源:互联网 发布:伊修巴尔歼灭战 知乎 编辑:程序博客网 时间:2024/06/10 16:22
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.
按照单链表的顺序从头到尾遍历链表,同时创建新的节点,记录新节点与旧节点的对应关系,最后再一次从头到尾遍历节点处理rand节点的值。
/** * 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; 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
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- 个人学习(一)
- 【计算机视觉】摄像机标定2 原理篇
- 绕过验证码,使用chrome的已存在的cookie访问网站
- Ubuntu14.04系统下无法连接Wi-Fi无线网以及安装BCM43142网卡驱动的解决方案
- java并发编程实践之线程安全性
- Copy List with Random Pointer
- 解析XML文件信息
- 偶遇深圳图书馆
- 【EasyUI】初识之Datagrid(一)
- myeclipse 10配置jboss 7.1.1无法启动Error: Could not create the Java Virtual Machine
- [leetcode]Add Two Numbers
- MapReduce执行过程中的数据流程:
- printf/sprintf/fprintf
- Linux之文件备份--cp