[LeetCode] 138. Copy List with Random Pointer
来源:互联网 发布:苹果手机九格切图软件 编辑:程序博客网 时间:2024/05/14 02:55
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.
问题描述:
给定一个单链表,在传统的单链表的基础之上,每个节点还增加了一个random指针,指向链表中的任意一个节点或者null。
请深度复制整个链表。
RandomListNode *copyRandomList(RandomListNode *head) { if (head == nullptr) return nullptr; RandomListNode *newhead = new RandomListNode(head->label); RandomListNode *pold = head, *pnew = newhead; unordered_map<RandomListNode *, RandomListNode *> map; map[pold] = pnew;// 遍历链表,为新旧链表对应位置上的节点建立一个映射关系。 while (pold->next != nullptr) { pnew->next = new RandomListNode(pold->next->label); pold = pold->next; pnew = pnew->next; map[pold] = pnew; } // 由于新链表所有的节点都已经存在。故我们可以用映射关系为每个新节点设置其random指针。 pold = head, pnew = newhead; while (pold != nullptr) { assert(!map.count(pold->random)); pnew->random = map[pold->random]; pold = pold->next; pnew = pnew->next; } return newhead; }
阅读全文
0 0
- 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
- 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
- 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
- [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
- leetcode 138. Copy List with Random Pointer
- Leetcode 138. Copy List with Random Pointer
- Windows x64 栈帧结构
- 412. Fizz Buzz
- 正则表达式中 .* 与 .*? 的区别
- python中format使用
- windows下配置python的numpy,scipy,pygame
- [LeetCode] 138. Copy List with Random Pointer
- web.xml基础详解
- 5-51 两个有序链表序列的合并 (20分)
- Jackson系统给您介绍何为娱乐文化优先股!
- 漫步数理统计三十四——顺序统计量
- [反演 数论] 51Nod 1355 斐波那契的最小公倍数
- TensorFlow学习笔记之读取数据概述
- Lintcode78 Longest Common On Prefix solution 题解
- Android自动化测试-Monkey性能测试