C Programming Data Structures
π Week 5: Data Structures in C
This week marks the culmination of our C journey, focusing on advanced data structures. While initial steps felt challenging, we'll now apply previous concepts like pointers to build more complex and efficient ways of organizing data. The world is full of abstract data types (ADTs) which are conceptual models for structuring information, independent of their underlying implementation details. Data structures, on the other hand, are the concrete implementations using variables, pointers, and functions.
ποΈ Abstract Data Types: Queues & Stacks
Abstract Data Types (ADTs) define a logical view of data and the operations that can be performed on it, without specifying how the data is physically stored or how the operations are implemented.
πΆββοΈ Queues: First-In, First-Out (FIFO)
A queue is an ADT that operates on a First-In, First-Out (FIFO) principle. The first element added to the queue is the first one to be removed.
Real-world examples:
A line at a movie theater or for dinner.
Documents waiting to be printed in a printer queue.
Core Operations:
enqueue: Adds an element to the rear of the queue.dequeue: Removes an element from the front of the queue.
Implementation in C (Conceptual):
We could use a
structto represent a queue.This
structmight contain an array to holdpersonobjects (or any data type) and an integersizeto track the current number of elements in the queue.A
capacity(e.g.,const int CAPACITY = 50;) defines the maximum number of elements, whilesizedynamically reflects the current occupancy.
typedef struct
{
person people[CAPACITY]; // Array to store elements
int size; // Current number of elements
}
queue;π Stacks: Last-In, First-Out (LIFO)
A stack is an ADT that operates on a Last-In, First-Out (LIFO) principle. The last element added to the stack is the first one to be removed.
Real-world examples:
A stack of sweaters in a drawer: the last one put on top is the first one taken out.
Trays in a dining hall: people take from the top.
An email inbox (like Gmail): new emails appear at the top and are often addressed first.
Core Operations:
push: Adds an element to the top of the stack.pop: Removes an element from the top of the stack.
Implementation in C (Conceptual):
Similar to a queue, a
structcould define a stack with an array and asizevariable.The key difference lies in how
pushandpopoperations are implemented to ensure the LIFO property, typically by always operating on the highest index of the underlying array.
Queues are FIFO (First-In, First-Out), while Stacks are LIFO (Last-In, First-Out). This property is independent of the underlying implementation.
π Linked Lists: Dynamic Data Structures
Arrays are simple and contiguous in memory, but their fixed size is a significant limitation. Linked lists offer a dynamic alternative by using pointers to connect data elements that can be scattered throughout memory.
β οΈ Limitations of Arrays
Fixed Size: Must declare the size in advance (e.g.,
int list[3];).Contiguous Memory: Elements must be stored back-to-back in memory.
Resizing: If more space is needed, a new, larger array must be allocated, and all existing elements copied over. This is a time-consuming (linear time) operation.
malloccan allocate a block of contiguous memory.realloccan attempt to resize an existing memory block. If successful and there's space, it expands the block in place; otherwise, it allocates a new block, copies the data, and frees the old one.
Memory Waste: Over-allocating memory for arrays to avoid resizing can lead to wasted space.
β¨ Introduction to Linked Lists
A linked list is a dynamic data structure where elements are not stored contiguously in memory. Instead, each element (called a node) contains both the data and a pointer (or "link") to the next node in the sequence.
Components:
Node: A structure that holds both the data and a pointer to the next node.
Data: The actual value stored in the node (e.g., an integer, a
personstruct).nextpointer: A pointer to the memory address of the subsequent node.NULL: Thenextpointer of the last node in the list points toNULL, signifying the end of the list.headpointer: A special pointer that always points to the first node of the linked list. If the list is empty, theheadpointer isNULL.
Advantages:
Dynamic Size: Can grow or shrink as needed without explicit resizing operations.
Efficient Memory Usage: Uses available memory locations wherever they exist, avoiding the need for large contiguous blocks.
Flexible: Can be used to build other complex data structures.
Disadvantages:
Increased Space: Each node requires extra space to store the pointer(s).
No Random Access: To access an element, you must traverse the list from the beginning, following the
nextpointers. This means searching takes linear time (O(n)).More Complex Code: Implementing linked lists (insertion, deletion, traversal) is more intricate than with arrays due to pointer manipulation.
π©βπ» Implementing a Node in C
A node in a linked list is typically implemented using a struct that contains the data and a pointer to another node of the same type.
typedef struct node
{
int number; // Data field (e.g., an integer)
struct node *next; // Pointer to the next node
}
node;The
struct node *next;declaration within thenodestruct requires thestruct nodeprefix becausenode(thetypedefalias) is not fully defined until the end of thetypedefstatement.
β‘οΈ The Arrow Operator (->)
When working with pointers to structs, the arrow operator (->) is a convenient shorthand.
(*ptr).field(dereferenceptrthen accessfield) is equivalent toptr->field.Example:
n->number = get_int();is cleaner than(*n).number = get_int();.
β Inserting Nodes into a Linked List
There are several ways to insert nodes into a linked list, each with different time complexities and implications for order:
Prepending (Inserting at the Beginning):
This is the most efficient way to insert into a singly linked list.
Algorithm:
Create a new node.
Set the new node's
nextpointer to point to the currentheadof the list.Update the
headpointer to point to the new node.me Complexity**: O(1) (constant time) because you always have direct access to the
head. wnside**: The list will be in reverse order of insertion (LIFO-like).mple: Prepending a new node 'n' to 'list' t = list; // New node points to the old start of the list n; // List now starts at the new node
Appending (Inserting at the End):
This maintains the order of insertion (FIFO-like).
Algorithm:
Create a new node.
If the list is empty, set the
headto the new node.Otherwise, traverse the list from the
headuntil you reach the last node (wherenextisNULL).Set the last node's
nextpointer to point to the new node.me Complexity**: O(n) (linear time) because you must traverse the entire list to find the end. timization**: Maintain a separate
tailpointer that always points to the last node. This makes appending O(1), but adds a small memory overhead and complexity to update thetailduring other operations.
Inserting in Sorted Order:
This ensures the list remains sorted after each insertion.
Algorithm:
Create a new node.
Case 1 (Empty List): If the list is empty, the new node becomes the
head.Case 2 (Prepend): If the new node's value is less than the
head's value, prepend the new node.Case 3 (Append/Middle): Traverse the list to find the correct insertion point (where the new node's value is between the current node and the next node). Adjust pointers to insert the new node.
me Complexity**: O(n) (linear time) in the worst case, as you might need to traverse most of the list.
π§Ή Freeing a Linked List
Properly freeing a linked list is crucial to prevent memory leaks. You must iterate through the list and free each node individually.
Caution: Once you
free(ptr),ptris no longer valid. You cannot accessptr->nextafter freeingptr.Algorithm:
Start with a temporary pointer (`ptr`) at the `head` of the list.
While `ptr` is not `NULL`: a. Create another temporary pointer (`tmp`) and store `ptr->next` in it (the address of the *next* node). b. `free(ptr)` (free the *current* node). c. Update `ptr = tmp` (move to the *next* node).
π³ Trees: Hierarchical Data Structures
A tree is a non-linear, hierarchical data structure that organizes data in a tree-like fashion, with a root node at the top and child nodes branching downwards. Unlike linked lists, trees are two-dimensional.
π² Binary Search Trees (BSTs)
A Binary Search Tree (BST) is a special type of tree where each node has at most two children: a left child and a right child. The key property of a BST is:
All values in the left subtree of a node are less than the node's value.
All values in the right subtree of a node are greater than (or equal to) the node's value.
Node Structure:
Each node contains the data, a pointer to its left child, and a pointer to its right child.
Advantages:
Efficient Searching: Because of the ordering property, BSTs allow for binary search, leading to O(log n) time complexity for searching, insertion, and deletion (in a balanced tree).
Dynamic: Can grow and shrink as needed, similar to linked lists.
Disadvantages:
Space Overhead: Each node requires two pointers, increasing memory usage compared to a singly linked list.
Balancing Complexity: If elements are inserted in a sorted (or nearly sorted) order, the BST can degenerate into a linked list, leading to O(n) worst-case time complexity.
To maintain O(log n) performance, BSTs often require balancing algorithms (e.g., AVL trees, Red-Black trees) which add significant implementation complexity. These algorithms "rotate" parts of the tree to keep its height logarithmic.
Searching in a BST (Recursive Algorithm):
Start at the
root.If the
rootisNULL, the value is not found (base case).If the target value is less than the current node's value, recursively search the left subtree.
If the target value is greater than the current node's value, recursively search the right subtree.
If the target value equals the current node's value, the value is found.
π Dictionaries: Key-Value Pairs
A dictionary is an Abstract Data Type (ADT) that stores a collection of key-value pairs. Each unique key is associated with a specific value.
Real-world examples:
A traditional dictionary: word (key) associated with its definition (value).
A phonebook: name (key) associated with a phone number (value).
Core Operations:
insert(key, value): Adds a new key-value pair.lookup(key): Retrieves the value associated with a given key.delete(key): Removes a key-value pair.
Goal: Ideally, dictionaries should provide constant-time (O(1)) access to values based on their keys.
π² Hashing and Hash Tables
Hashing is a technique used to implement dictionaries efficiently.
Hash Function: A function that takes an input (a key) and converts it into a numerical index (a hash value) within a fixed-size array, often called a hash table.
Goal: Distribute keys evenly across the hash table to minimize collisions.
Example: For names, a simple hash function might use the first letter of the name to map it to an index (e.g., 'A' -> 0, 'B' -> 1, ..., 'Z' -> 25).
Hash Table: A data structure that uses a hash function to map keys to indices in an array (buckets). It's essentially an array of linked lists.
Components:
Array (Buckets): A fixed-size array where each element can store a pointer to a linked list.
Linked List (Chains): If multiple keys hash to the same index (a collision), they are stored in a linked list at that array index.
Advantages:
Average Case O(1) Access: With a good hash function and sufficient table size, searching, insertion, and deletion can approach constant time on average.
Dynamic Handling of Collisions: Linked lists allow for an arbitrary number of items to hash to the same bucket.
Disadvantages:
Worst Case O(n) Access: If all keys hash to the same bucket (due to a poor hash function or adverse input), the hash table degenerates into a single linked list, resulting in linear time operations.
Space Overhead: Requires memory for the array of pointers and for the linked list nodes.
Hash Function Quality: The performance heavily depends on the quality of the hash function; a bad hash function leads to many collisions and poor performance.
Initial Space Allocation: The array of buckets is of a fixed size, which needs to be determined upfront.
π§ Hash Function Design
A simple hash function might use the first letter of a word, convert it to uppercase, and subtract the ASCII value of 'A' to get an index between 0 and 25.
More sophisticated hash functions consider multiple characters, sum their ASCII values, or use more complex mathematical operations to produce a more uniform distribution of hash values, reducing collision probability.
While increasing the number of buckets (e.g., using three letters for 17,000+ buckets) reduces collision probability, it also increases memory consumption, potentially wasting space if many buckets remain empty.
Hash tables technically have a worst-case time complexity of O(n). However, with a well-designed hash function and a reasonable number of buckets, the average-case performance is practically O(1).
π³ Tries: Prefix Trees for String Retrieval
A trie (pronounced "try", short for "retrieval tree") is a specialized tree-like data structure used to store and efficiently retrieve strings. It can be thought of as a tree of arrays.
Structure:
Each node in a trie represents a character in a string.
Each node contains an array of pointers (typically 26 for the English alphabet), where each pointer corresponds to a possible next character.
A special marker (e.g., a boolean
is_wordflag or a non-NULLdata pointer) within a node indicates whether a word ends at that node.The entire trie starts with a
rootnode.
How it works:
To insert a word (e.g., "TOAD"), you traverse the trie character by character.
For 'T', you follow the pointer in the root's array corresponding to 'T'. If it's
NULL, create a new node.From the 'T' node, follow the pointer for 'O', then 'A', then 'D'.
At the 'D' node, mark it as the end of a word.
To search, you follow the same path. If you reach the end of the word and the final node is marked as a word, the word exists.
Node Structure:
Advantages:
True O(1) Access: Search, insertion, and deletion operations have a time complexity that depends only on the length of the key (string), not the total number of items in the trie. This is effectively constant time because string lengths have a practical upper bound.
Prefix Searching: Very efficient for finding all words with a common prefix.
Disadvantages:
Significant Space Overhead: Each node contains an array of pointers (e.g., 26 pointers for English alphabet), even if many of them are
NULL. This can consume a large amount of memory, especially for sparse datasets (where many possible character combinations don't exist in actual words).
Tries offer true constant-time (O(1)) operations for string-based keys, where the constant is the length of the string. This comes at the cost of high memory consumption.
βοΈ Time-Space Trade-offs
A recurring theme in computer science is the time-space trade-off:
Arrays:
Time: Fast access (O(1)) by index, but O(n) for insertion/deletion (if resizing or shifting is needed). O(log n) for search if sorted and binary search is used.
Space: Compact (contiguous), but fixed size can lead to waste or costly resizing.
Linked Lists:
Time: O(n) for search, O(1) for prepending, O(n) for appending.
Space: Dynamic, but uses more memory for pointers.
Binary Search Trees:
Time: O(log n) for search, insertion, deletion (if balanced). O(n) in worst-case (unbalanced).
Space: Uses more memory for two pointers per node.
Hash Tables:
Time: Average O(1) for search, insertion, deletion (with good hash function). Worst-case O(n).
Space: Uses memory for array of buckets and linked list nodes.
Tries:
Time: O(L) where L is the length of the key (effectively O(1)).
Space: Very high memory consumption due to arrays of pointers in each node.
Choosing the right data structure depends on the specific problem, the expected data characteristics, and the priorities for time efficiency versus memory usage.

Ask anything
We've read this whole study set, so questions about it get the best answers.