[LeetCode] Copy List with Random Pointer
2016-07-29 00:00
429 查看
https://oj.leetcode.com/problems/copy-list-with-random-pointer/
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.
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.
Analysis
Apparently, it’s not a difficult question to clone a linked list without an additional random pointer. For us, the trickier part, however, is to clone the random list node structure. My idea is using a HashTable.Code
/** * Author : Acjx * Email : zhoujx0219@163.com */ /** * 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: /** * @param head: The head of linked list with a random pointer. * @return: A new head of a deep copy of the list. */ RandomListNode *copyRandomList(RandomListNode *head) { RandomListNode *dummyHead = new RandomListNode(0); RandomListNode *p = head, *q = dummyHead; unordered_map<RandomListNode *, RandomListNode *> map; while (p != NULL) { q->next = new RandomListNode(p->label); map.insert(make_pair(p, q->next)); p = p->next; q = q->next; } p = head; q = dummyHead; while (p != NULL) { q->next->random = map[p->random]; p = p->next; q = q->next; } return dummyHead->next; } };
相关文章推荐
- Linux多线程之同步2 —— 生产者消费者模型
- 高性能服务器架构
- Nginx:配置指南(2)
- 数学图形(1.19)Doppler spiral螺线
- LINUX输入输出与文件
- Dynamic Programming | Set 2 (Optimal Substructure Property)
- Linux安装程序Anaconda分析(续)
- 标准管道(popen)
- Linux内存管理(2):内存描述
- Linux多线程之同步3
- HDFS架构
- Linux进程管理(3):总结
- Linux多线程之同步
- Linux系统管理实践(4):忘记登录密码或账号
- 服务器设计系列:架构综述
- Linux系统管理实践(5):Samba文件共享配置
- 编程实现Linux下的ls -l
- Linux系统管理实践(3):GRUB系统引导配置
- Linux信号处理2
- Linux之select系统调用_1