/** * 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 {//In order to be able to quickly locate a node, using deterministic mapping, the node of the replicated list is the next node of the original linked list Public:randomlistnode *copyrandomlist (
Randomlistnode *head) {//each node points to its corresponding node of the replication link so that the node can be quickly positioned if (!head) return NULL;
Randomlistnode *p,*q;
P=head;
while (p) {q=new randomlistnode (P->label);
q->next=p->next;
p->next=q;
p=q->next;
} P=head;
while (p) {q=p->next;
if (p->random) q->random=p->random->next;
p=q->next;
} P=head;
randomlistnode*head2=p->next;
Q=head2;
while (p) {p->next=q->next;
p=p->next;
if (p) { q->next=p->next;
q=q->next;
}} return head2; }
};
Clone Graph :
Similarly, for the copy of the graph, you must find a way to map the nodes in the new diagram, to quickly locate the address of the new node, so that the new node points to the new node. The map map is used here. Consider that the label of the graph node may be duplicated (the subject does not repeat), and the node address is not duplicated, so the old and new nodes are key-value pairs.
/**
* Definition for undirected graph.
* struct Undirectedgraphnode {
* int label;
* vector<undirectedgraphnode *> neighbors;
* undirectedgraphnode (int x): label (x) {};
* };
*
/class Solution {public
:
map<undirectedgraphnode*,undirectedgraphnode*>mp;
Map<undirectedgraphnode*,undirectedgraphnode*>::iterator BG;
undirectedgraphnode* Dfs (undirectedgraphnode*p) {
if (!p) return NULL;
if ((Bg=mp.find (p))!=mp.end ())
return bg->second;
Undirectedgraphnode *q;
Mp[p]=q=new Undirectedgraphnode (P->label);
for (int i=0,m=p->neighbors.size (); i<m;++i) {
q->neighbors.push_back (DFS (p->neighbors[i]));
}
return q;
}
Undirectedgraphnode *clonegraph (Undirectedgraphnode *node) {
if (!node) return NULL;
DFS (node);
return mp[node];
}
;