133. Clone Graph 138. Copy List with Random Pointer 拷贝图和链表

时间:2021-06-24 23:17:43

133. Clone Graph

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

OJ's undirected graph serialization:

Nodes are labeled uniquely.

We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.

As an example, consider the serialized graph {0,1,2#1,2#2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:

       1
/ \
/ \
0 --- 2
/ \
\_/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node == NULL)
return NULL;
UndirectedGraphNode *cloneNode = new UndirectedGraphNode(node->label);
map<UndirectedGraphNode*, UndirectedGraphNode*> m;
m[node] = cloneNode;
queue<UndirectedGraphNode*> q;
q.push(node);
while(!q.empty())
{
UndirectedGraphNode *t = q.front();
q.pop();
for(int i = ; i < t->neighbors.size(); i++)
{
UndirectedGraphNode *neighbor = t->neighbors[i];
if(m.find(neighbor) == m.end())
{
UndirectedGraphNode *p = new UndirectedGraphNode(neighbor->label);
m[neighbor] = p;
m[t]->neighbors.push_back(p);
q.push(neighbor);
}
else
{
m[t]->neighbors.push_back(m[neighbor]);
}
}
}
return cloneNode;
}
};

138. 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.

/**
* 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) {}
* };
*/

(1)

* Consider we have a linked list as below:
*
* node1->random = node2;
* node2->random = node1;
* node3->random = node1;
*
* +-------------+
* | v
* +-------+ +-------+ +-------+
* | node1 |----> node2 |----> node3 |--->NULL
* +-------+ +-------+ +-------+
* ^ ^ | |
* | +-----------+ |
* +--------------------------+
*
*
* To copy the list,
*
* 1) We insert a new node for each node's next position
*
*
* +-------------------------+
* | v
* +--+----+ +-----+ +-------+ +-----+ +-------+ +-----+
* | node1 |---> | NEW |----> node2 |---> | NEW |----> node3 |---> | NEW | ---> NULL
* +-------+ +-----+ +---+---+ +-----+ +--+----+ +-----+
* ^ ^ | |
* | +-----------------------+ |
* +--------------------------------------------------+
*
* 2) Then, we can construt the new node's random pointer:
*
* (node1->next) -> random = (node1->random) -> next;
*
* 3) After we take out all of the "NEW" node to finish the copy.

class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
RandomListNode *p = NULL, *h=NULL, *t=NULL;
if (head == NULL){
return NULL;
} //creat a new node for each node and insert its next
p = head;
while ( p != NULL){
RandomListNode *node = new RandomListNode(p->label);
node->next = p->next;
p->next = node;
p = node->next;
} //copy random pointer for each new node
p = head;
while (p != NULL){
if (p->random != NULL){
p->next->random = p->random->next;
}
p = p->next->next;
} //break to two list
p = head;
h = t = head->next;
while ( p != NULL ){
p->next = p->next->next;
if (t->next!=NULL){
t->next = t->next->next;
} p = p->next;
t = t->next;
} return h;
}
};

(2)

* Considering we have a link as below:
*
*
* +-------------+
* | v
* +-------+ +-------+ +-------+
* | node1 |----> node2 |----> node3 |--->NULL
* +-------+ +-------+ +-------+
* ^ ^ | |
* | +-----------+ |
* +--------------------------+
*
* 1) Using a map to store each node's random pointer's position
*
* map[node1->random] = 1;
* map[node2->random] = 0;
* map[node3->random] = 0;
*
* 2) Clone the linked list (only consider the next pointer)
*
* new1 --> new2 --> new3 --> NULL
*
* 3) Using an array to strore the order of the cloned linked-list
*
* v[0] = &new1
* v[1] = &new2
* v[2] = &new3
*
* 4) Then we can clone the random pointers.
*
* new->random = v [ map[node->random] ]

class MySolution {
public:
RandomListNode *copyRandomList(RandomListNode *head) { RandomListNode *p = NULL, *h=NULL, *t=NULL;
//using a map to store the random pointer's postion.
map<RandomListNode*, int> m;
//construct the map
int pos =;
for ( p = head; p != NULL; p = p->next, pos++){
m[p] = pos;
} //clone the linked list (only consider the next pointer)
//and using a vector to store each node's postion.
vector<RandomListNode*> v;
for (p = head; p != NULL; p = p->next){
RandomListNode *node = new RandomListNode(p->label);
v.push_back(node);
if (h==NULL){
h = t = node;
}else{
t->next = node;
t = node;
}
} //p => source link head
//t => new link head
//move the p and t synchronously, and
// t->random = vector[ map[p->random] ];
for (t=h, p = head; t!=NULL && p!= NULL; p=p->next, t=t->next){
if (p->random!=NULL) {
pos = m[p->random];
t->random = v[pos];
}
} return h; }
};

133. Clone Graph 138. Copy List with Random Pointer 拷贝图和链表的更多相关文章

  1. &lbrack;LeetCode&rsqb; 138&period; Copy List with Random Pointer 拷贝带随机指针的链表

    A linked list is given such that each node contains an additional random pointer which could point t ...

  2. &lbrack;LeetCode&rsqb; 138&period; Copy List with Random Pointer 拷贝带有随机指针的链表

    A linked list is given such that each node contains an additional random pointer which could point t ...

  3. Java for LeetCode 138 Copy List with Random Pointer

    A linked list is given such that each node contains an additional random pointer which could point t ...

  4. 138&period; Copy List with Random Pointer &lpar;Graph&comma; Map&semi; DFS&rpar;

    A linked list is given such that each node contains an additional random pointer which could point t ...

  5. leetcode 138&period; Copy List with Random Pointer ----- java

    A linked list is given such that each node contains an additional random pointer which could point t ...

  6. 138&period; Copy List with Random Pointer

    A linked list is given such that each node contains an additional random pointer which could point t ...

  7. 【LeetCode】138&period; Copy List with Random Pointer

    题目: A linked list is given such that each node contains an additional random pointer which could poi ...

  8. 138&period; Copy List with Random Pointer &lpar;not do it by myself&rpar;

    A linked list is given such that each node contains an additional random pointer which could point t ...

  9. leetcode 138&period; Copy List with Random Pointer复杂链表的复制

    python代码如下: # Definition for singly-linked list with a random pointer. # class RandomListNode(object ...

随机推荐

  1. jsoup html采集器

    package com.forex.collect; import java.io.IOException;import java.util.HashMap;import java.util.Iter ...

  2. PLSQL&lowbar;数据泵导入进度查看Impdp&sol;Expdp Status(案例)

    20150701 Created By BaoXinjian

  3. &lbrack;Jobdu&rsqb; 题目1516 &colon; 调整数组顺序使奇数位于偶数前面

    void diffOddAndEven(int a[], int n) { , high = n - ; int pivot; while (low < high) { == &&amp ...

  4. Apache FtpServer 实现文件的上传和下载

    1 下载需要的jar包 Ftp服务器实现文件的上传和下载,主要依赖jar包为: 2 搭建ftp服务器 参考Windows 上搭建Apache FtpServer,搭建ftp服务器 3 主要代码 在ec ...

  5. Oracle trunc&lpar;&rpar;函数的用法及四舍五入 round函数

    --Oracle trunc()函数的用法/**************日期********************/1.select trunc(sysdate) from dual  --2011 ...

  6. &lpar;NO&period;00002&rpar;iOS游戏精灵战争雏形&lpar;一&rpar;

    原本想做一个复杂点的平面动作游戏,可以觉得还是有点把握不了.还是先从简单的原型开始吧. 构思中的精灵战争(SpriteWar)是一个类似FC时代的小游戏,可以造兵,可以捕获敌兵.原本还想加上保卫老巢的 ...

  7. Python练习:关于递归的经典实例设计

    (一)裴波拉契数列 利用递归算法获得裴波拉契数列前N个值的结果: #裴波拉契数列,通过递归计算 def fb(n): if n <=0: res = 0 elif n ==1: res = 1 ...

  8. Unable to execute &&num;39&semi;doFinal&&num;39&semi; with cipher instance

    今天项目启动后登录项目,突然爆出Unable to execute 'doFinal' with cipher instance错误.清除cookie登录测试,又不报错了,以前也见过类似问题,因为不影 ...

  9. jquery-2&period;0&period;3 源码分析 整体架构

    关键 var jQuery = function( selector, context ) { return new jQuery.fn.init(); } jQuery.fn = jQuery.pr ...

  10. MongoDB的学习--索引类型和属性(转)

    原文链接:MongoDB的学习--索引类型和属性 索引类型 MongDB的索引分为以下几种类型:单键索引.复合索引.多键索引.地理空间索引.全文本索引和哈希索引 单键索引(Single Field I ...