-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopy_List_with_Random_Pointer.cpp
More file actions
58 lines (50 loc) · 1.62 KB
/
Copy_List_with_Random_Pointer.cpp
File metadata and controls
58 lines (50 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Source : https://oj.leetcode.com/problems/copy-list-with-random-pointer/
// Author : zheng yi xiong
// Date : 2014-12-01
/**********************************************************************************
*
* 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.
*
**********************************************************************************/
#include "stdafx.h"
#include <map>
using namespace std;
struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
class CCopy_List_with_Random_Pointer {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if (NULL == head)
{
return NULL;
}
map<RandomListNode *, RandomListNode *> map_randomlist;
RandomListNode *pCopyHead = new RandomListNode(head->label);
map_randomlist.insert(map<RandomListNode *, RandomListNode *>::value_type(head, pCopyHead));
RandomListNode *pSrcNode = head->next;
RandomListNode *pDetNode = pCopyHead;
while (NULL != pSrcNode)
{
pDetNode->next = new RandomListNode(pSrcNode->label);
map_randomlist.insert(map<RandomListNode *, RandomListNode *>::value_type(pSrcNode, pDetNode->next));
pSrcNode = pSrcNode->next;
pDetNode = pDetNode->next;
}
pSrcNode = head;
pDetNode = pCopyHead;
while (NULL != pSrcNode)
{
if (NULL != pSrcNode->random)
{
pDetNode->random = map_randomlist[pSrcNode->random];
}
pSrcNode = pSrcNode->next;
pDetNode = pDetNode->next;
}
return pCopyHead;
}
};