pointers-memory · advanced · ~15 min
Clone cyclic pointer graphs using pointer-to-pointer address translation maps.
Deep-cloning complex linked structures containing cycles (e.g. directed graphs) requires maintaining a mapping from old pointers to newly allocated clones to prevent infinite recursion and duplicate node creations.
Implement:
struct gnode {
int val;
size_t num_neighbors;
struct gnode *neighbors[4];
};
struct gnode *clone_graph(const struct gnode *start, struct gnode *pool, size_t pool_cap, size_t *pool_used);
Clone the connected graph component reachable from start into nodes allocated from pool.
start == NULL, pool == NULL, pool_used == NULL, or pool_cap == 0, return NULL.*pool_used = 0.pool[(*pool_used)++]. If *pool_used > pool_cap, fail and return NULL.(old_pointer -> new_pointer) to ensure each original node is cloned exactly once.neighbors in cloned nodes to point to their corresponding cloned neighbors.start.start: root node pointer; pool: pre-allocated node slab; pool_cap: pool capacity; pool_used: allocation counter.
Returns pointer to cloned root node, or NULL on error.
C11 freestanding. Support cycles without infinite loops.
#include <stddef.h>
/* The harness provides:
struct gnode {
int val;
size_t num_neighbors;
struct gnode *neighbors[4];
};
*/
struct gnode *clone_graph(const struct gnode *start, struct gnode *pool, size_t pool_cap, size_t *pool_used) {
(void)start; (void)pool; (void)pool_cap; (void)pool_used;
return NULL;
}
Infinite recursion on cycles; allocating duplicate nodes for the same original pointer.
Self-referencing node (cycle of length 1); mutual cycles; linear graph; NULL input.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.