forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcopyListWithRandomPointer.cpp
102 lines (86 loc) · 2.63 KB
/
copyListWithRandomPointer.cpp
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Source : https://oj.leetcode.com/problems/copy-list-with-random-pointer/
// Author : Hao Chen
// Date : 2014-06-18
/**********************************************************************************
*
* 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) {}
* };
*/
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;
}
};
class MySolution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
RandomListNode *p = NULL, *h=NULL, *t=NULL;
map<RandomListNode*, int> m;
int pos =0;
for ( p = head; p != NULL; p = p->next, pos++){
m[p] = pos;
}
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;
}
}
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;
}
};