A ground-up implementation of essential C containers, built to understand memory, pointers, and systems programming
Personal journey to master pointer arithmetic, memory ownership, and binary serialization in C. The repository contains generic, reusable data structures (Vector, List, Map, BST) and demonstrates them solving real LeetCode problems
- Saving BST to file: function callback on a BFS traversal. The function captures
keyandval's binary data, as well as their sizes, into binary format (usingfread,fwrite) - Loading BST from file: insert the captured data in the exact BFS order to rebuild the tree identically
- BFS traversal made use of
queue_tthat wrapslist_t
- Vector stores data contiguously using
memcpy, It's more cache-friendly, but cannot store variable-length strings directly (store pointers to strings instead) - Map, List, and BST allocate their own deep copies of your data. Each node owns its own memory and knows its size (
k_szandv_sz), which is critical for storing dynamic strings
Binary Search Tree taught C pointer indirection:
node*= A pointer to a node (used to read the address)node**= A pointer to a pointer (used to modify the address stored in the parent'sleft/rightslot)- This made it possible to insert and delete iteratively without tracking
prevpointers and also handled theroot == NULLcase elegantly
- Wrote a custom
run.shscript tht simulates an "interpreted" feel for rapid C prototyping - Would still use a build system for bigger projects, scripting was simpler in this case
| Container | File | Key Trait |
|---|---|---|
| Vector | vector_t |
Contiguous memory, memcpy storage, dynamic resizing |
| Singly Linked List | list_t |
O(1) push/pop from front/back (no dummy head, no prev pointer yet) |
| Hash Map | map_t |
Chaining, dynamic resizing, generic key/value comparison |
| Binary Search Tree | bst_t |
Iterative insertion/removal using double pointers |
| Queue | queue_t |
Wrapper around list_t (FIFO) |
This repository uses assertion-based tests (see test.c) to validate the containers, some are also used in solving Leetcode problems which further demonstrate their reliability
Using my custom containers to solve Leetcode problems. The solutions are not the most efficient but they are enough to showcase the use of custom containers in real-world scenarios
| File | Problem | Container Used |
|---|---|---|
isomorphic_strings.c |
Isomorphic Strings | map_t |
contains_duplicate.c |
Contains Duplicate | bst_t |
valid_anagram |
Valid Anagram | vector_t |
two_sum.c |
Two Sum | map_t |
- GCC or Clang
- Make (optional, but
bashis required for the build scripts)
# clone the repo and navigate to the root
git clone git@github.com:gmpikazu/c-data-structures.git
cd c-data-structures
# run the examples
./run.sh examples/contains_duplicates.c
./run.sh examples/isomorphic_strings.c
./run.sh examples/valid_anagram.c
./run.sh examples/two_sum.c
# run the test file
./run.sh test.c # will generate *.bin files for BST save/load verification