当前位置:网站首页>Replication of complex linked list
Replication of complex linked list
2022-07-27 16:25:00 【Cute rain】
Title Description : Please implement copyRandomList function , Copy a complex list . In complex linked list , Each node has one next The pointer points to the next node , One more random The pointer points to any node in the list or NULL;
Question : The copy of linked list can directly traverse the linked list , Create a new node implementation , there random What does the pointer do ?
Problem solving : As the title says , What is needed here is the replication of complex linked lists , there random It doesn't matter what the pointer does , The important thing is how to copy the random pointer correctly .
Ideas : Using the query characteristics of hash table , Consider building the key value mapping relationship between the original linked list node and the corresponding node of the new linked list , Then traverse the nodes of the new linked list next and random Reference points to . In other words, traverse both sides , The first time, only build new nodes , Build a new node for the second time next and cur.
The illustration :

Code implementation :
Node* copyRandomList(Node* head)
{
if (head == NULL)return NULL;
unordered_map<Node*, Node*>map;
Node* cur = head;
while (cur != NULL)
{
map[cur] = new Node(cur->val);
cur = cur->next;
}
cur = head;
while (cur != NULL)
{
map[cur]->next = map[cur->next];
map[cur]->random = map[cur->random];
cur = cur->next;
}
return map[head];
}
边栏推荐
猜你喜欢
随机推荐
EXE程序加密锁
SolidWorks simulation curve attribute setting
Content ambiguity occurs when using transform:translate()
Example of the task submitted by the Flink packer
Two methods of generating excel table with PHP
DRF learning notes (V): viewset
2.2 JMeter基本元件
Delete node quickly and efficiently_ modules
Join hands with sifive, Galanz will enter the semiconductor field! Exposure of two self-developed chips
Crmeb Pro v1.4 makes the user experience more brilliant!
MapReduce instance (I): wordcount
Use of arrow function
word中插入度的方法
Boolean value
Introduction to JWT
TP5 rewrite paging
企业运维安全就用行云管家堡垒机!
Redis简介与使用
Yys mouse connector
Sudden! 28 Chinese entities including Hikvision / Dahua / Shangtang / Kuangshi / ITU / iFLYTEK have been blacklisted by the United States









