File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ /**
3
+ * Definition for a Node.
4
+ * struct Node {
5
+ * int val;
6
+ * int numNeighbors;
7
+ * struct Node** neighbors;
8
+ * };
9
+ */
10
+
11
+ struct Node * create_node (int val , int numNeighbors ) {
12
+ struct Node * node = (struct Node * )malloc (sizeof (struct Node ));
13
+ node -> val = val ;
14
+ node -> numNeighbors = numNeighbors ;
15
+ if (numNeighbors > 0 ) {
16
+ node -> neighbors = (struct Node * * )malloc (numNeighbors * sizeof (struct Node * ));
17
+ } else {
18
+ node -> neighbors = NULL ;
19
+ }
20
+ return node ;
21
+ }
22
+
23
+ struct Node * clone_node (struct Node * s , struct Node * * hashset ) {
24
+
25
+ if (s == NULL ) return s ;
26
+ if (hashset [(s -> val ) - 1 ] != NULL ) return hashset [(s -> val ) - 1 ];
27
+
28
+ struct Node * new_node = create_node (s -> val , s -> numNeighbors );
29
+ hashset [(s -> val ) - 1 ] = new_node ;
30
+ for (int i = 0 ; i < s -> numNeighbors ; i ++ ) {
31
+ new_node -> neighbors [i ] = clone_node (s -> neighbors [i ], hashset );
32
+ }
33
+ return new_node ;
34
+ }
35
+
36
+ struct Node * cloneGraph (struct Node * s ) {
37
+
38
+ struct Node * * hashset = (struct Node * * )malloc (100 * sizeof (struct Node * ));
39
+ for (int i = 0 ; i < 100 ; i ++ ) {
40
+ hashset [i ] = NULL ;
41
+ }
42
+ struct Node * s_clone = clone_node (s , hashset );
43
+ free (hashset );
44
+ return s_clone ;
45
+ }
You can’t perform that action at this time.
0 commit comments