File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Definition for singly-linked list with a random pointer.
3
+ * struct RandomListNode {
4
+ * int label;
5
+ * RandomListNode *next, *random;
6
+ * RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
7
+ * };
8
+ */
9
+ class Solution {
10
+ public:
11
+ RandomListNode *copyRandomList (RandomListNode *head) {
12
+ // Note: The Solution object is instantiated only once and is reused by each test case.
13
+ RandomListNode *ret = NULL , *tmp = head, *entry = NULL ;
14
+ RandomListNode **pCur = &ret;
15
+ while (tmp) {
16
+ entry = tmp;
17
+ tmp = tmp->next ;
18
+ entry->next = new RandomListNode (entry->label );
19
+ entry->next ->next = tmp;
20
+ }
21
+
22
+ tmp = head;
23
+ while (tmp) {
24
+ entry = tmp->next ;
25
+ if (tmp->random )
26
+ entry->random = tmp->random ->next ;
27
+ tmp = entry->next ;
28
+ }
29
+
30
+ tmp = head;
31
+ while (tmp) {
32
+ entry = tmp->next ;
33
+ *pCur = entry;
34
+ tmp->next = entry->next ;
35
+ tmp = tmp->next ;
36
+ pCur = &((*pCur)->next );
37
+ }
38
+ return ret;
39
+ }
40
+ };
You can’t perform that action at this time.
0 commit comments