内容简介:第一次遍历链表的时候,复制旧链表的节点值建立一个新的链表,同时定义一个 unordered_map 作为哈希表,哈希表的键为旧链表的节点指针,值为新链表的节点指针。然后,第二次遍历链表,访问旧链表节点的随机指针,然后以此为键从 map 中取出对应的新链表节点指针,这也就是当前新链表节点的随机指针。获取更多精彩,请关注「seniusen」!
2. 解答
第一次遍历链表的时候,复制旧链表的节点值建立一个新的链表,同时定义一个 unordered_map 作为哈希表,哈希表的键为旧链表的节点指针,值为新链表的节点指针。
然后,第二次遍历链表,访问旧链表节点的随机指针,然后以此为键从 map 中取出对应的新链表节点指针,这也就是当前新链表节点的随机指针。
/**
* 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) {
unordered_map<RandomListNode *, RandomListNode *> nodemap;
RandomListNode *temp = head;
RandomListNode *new_head = new RandomListNode(0); //哨兵节点,方便操作
RandomListNode *copy_temp = new_head;
// 建立新链表
while (temp)
{
copy_temp->next = new RandomListNode(temp->label);
nodemap[temp] = copy_temp->next;
temp = temp->next;
copy_temp = copy_temp->next;
}
RandomListNode *random_temp = NULL;
temp = head;
copy_temp = new_head->next;
// 填充新链表的随机指针
while (temp)
{
random_temp = temp->random;
if (random_temp != NULL) copy_temp->random = nodemap[random_temp];
else
copy_temp->random = NULL;
temp = temp->next;
copy_temp = copy_temp->next;
}
return new_head->next;
}
};
复制代码
获取更多精彩,请关注「seniusen」!
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 「复制带随机指针的链表」的一个很巧妙解法
- NULL 指针、零指针、野指针
- 将数组和矩阵传递给函数,作为C中指针的指针和指针
- C语言指针数组和数组指针
- python(函数指针和类函数指针)
- C++ 基类指针和派生类指针之间的转换
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Beginning ASP.NET 4 in C# and Vb
Imar Spaanjaars / Wrox / 2010-3-19 / GBP 29.99
This book is for anyone who wants to learn how to build rich and interactive web sites that run on the Microsoft platform. With the knowledge you gain from this book, you create a great foundation to ......一起来看看 《Beginning ASP.NET 4 in C# and Vb》 这本书的介绍吧!