-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopyListwithRandomPointer.cpp
More file actions
executable file
·65 lines (59 loc) · 1.54 KB
/
CopyListwithRandomPointer.cpp
File metadata and controls
executable file
·65 lines (59 loc) · 1.54 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
59
60
61
62
63
64
65
//
// CopyListwithRandomPointer.cpp
// leetcode
//
// Created by witwolf on 7/25/15.
// Copyright (c) 2015 witwolf. All rights reserved.
//
#include <vector>
#include <map>
using namespace std;
/**
* 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) {
if(head == NULL){
return NULL;
}
RandomListNode *p = head;
vector<RandomListNode*> nodes;
map<RandomListNode*,int> nodePos;
int pos = 0;
while(p){
nodes.push_back(p);
nodePos[p] = pos++;
p = p->next;
}
vector<int> randomPos ;
p = head;
while(p){
if(p->random){
randomPos.push_back(nodePos[p->random]);
}else{
randomPos.push_back(-1);
}
p = p->next;
}
vector<RandomListNode*> newNodes;
p = head;
while(p){
newNodes.push_back(new RandomListNode(p->label));
p = p->next;
}
newNodes.push_back(NULL);
for(pos = 0 ; pos < newNodes.size() - 1 ; pos++){
newNodes[pos]->next = newNodes[pos+1];
if(randomPos[pos] != -1){
newNodes[pos]->random = newNodes[randomPos[pos]];
}
}
return newNodes[0];
}
};