Stacks and Queues
Data Structures and Memory Management in C
Data structures determine how information is organized in memory and what operations can be performed efficiently. The same abstract data type can often be implemented in several concrete ways, and each implementation creates trade-offs involving speed, memory usage, flexibility, and code complexity.
A central theme is that improving one characteristic often requires sacrificing another:
Arrays provide fast access and support efficient binary search, but their size is difficult to change.
Linked lists can grow and shrink dynamically, but searching them is slower.
Trees can combine dynamic growth with logarithmic search, but they require additional pointers and careful balancing.
Hash tables can provide near-constant-time lookup, but collisions and memory usage must be managed.
Tries can achieve constant-time lookup relative to the number of stored items, but often use substantial amounts of memory.
Abstract Data Types and Concrete Data Structures
An abstract data type describes what a structure does and what operations it supports, without specifying exactly how it is implemented.
For example, a queue is defined by its ordering behavior and its operations:
New elements enter at one end.
Existing elements leave at the other end.
The first element inserted is the first element removed.
The queue could be implemented using:
An array
A linked list
A dynamically resized block of memory
Another structure built from multiple data structures
The abstract behavior remains the same even though the underlying implementation differs.
A data structure, in contrast, is a concrete arrangement of data in computer memory. It specifies:
How values are stored
How values are connected
How memory is allocated
How operations such as insertion, deletion, and searching are performed
An abstract data type specifies the behavior and operations a structure provides; a data structure specifies how those behaviors are implemented in memory.
Queues and Stacks
Queues
A queue models a line of people waiting for service. The person who arrives first should normally be served first.
A queue follows the FIFO rule:
FIFO means “first in, first out.” The first element inserted into the queue is the first element removed.
Examples include:
People waiting at a store
Print jobs waiting for a printer
Tasks waiting for a processor
Network packets waiting to be handled
Salads waiting on a restaurant pickup shelf
Queue operations
The two fundamental queue operations are:
Enqueue: add an element to the back of the queue
Dequeue: remove an element from the front of the queue
The operation names are sometimes abbreviated as enqueue and dequeue, or informally as enqueue and dequeue equivalents.
A queue is useful whenever fairness or arrival order matters. Processing elements in FIFO order prevents newer elements from continuously being served before older ones.
Stacks
A stack models a collection in which the most recently added item is removed first.
A stack follows the LIFO rule:
LIFO means “last in, first out.” The last element inserted into the stack is the first element removed.
Examples include:
A pile of clothing
A stack of cafeteria trays
Recently received email displayed at the top of an inbox
Function calls stored during program execution
Undo histories in software
Stack operations
The two fundamental stack operations are:
Push: place an element on top of the stack
Pop: remove the top element from the stack
Stacks are convenient when the newest item is the easiest or most appropriate item to access. However, older elements can be neglected if new elements are continually added on top.
Arrays
An array is a contiguous block of memory containing elements of the same type. The elements are stored directly next to one another.
For example, an integer array containing 1, 2, and 3 might be represented in C as:
int list[3];
list[0] = 1;
list[1] = 2;
list[2] = 3;C arrays use zero-based indexing:
The first element is at index 0.
The second element is at index 1.
The third element is at index 2.
The array’s values occupy consecutive memory locations. If each integer occupies the same number of bytes, the address of an element can be calculated using its index.
Strengths of arrays
Arrays provide several important advantages:
Elements are stored contiguously.
Accessing an element by index is fast.
The address of any element can be computed using arithmetic.
Binary search can be performed efficiently on a sorted array.
The structure is relatively simple to implement.
Accessing an array element by index takes constant time:
If an array is sorted, binary search can repeatedly divide the search space in half, resulting in:
where n is the number of elements.
Fixed-size limitation
A conventional C array has a size determined when it is declared:
int list[3];This declaration reserves enough space for exactly three integers. It does not guarantee that additional usable memory exists immediately after the array.
If a fourth value is needed, the program cannot safely write to list[3] unless space for that element was already allocated. Writing beyond the array’s bounds can overwrite unrelated data and produce undefined behavior.
This creates a design problem:
Allocating too little space prevents the structure from growing.
Allocating too much space wastes memory.
The programmer must often choose the size before the program runs.
If the array must be enlarged, the program generally has to:
Allocate a larger block of memory.
Copy the old elements into the new block.
Add the new element.
Free the old block.
For a large array, copying all existing elements can be expensive.
Dynamic Memory Allocation
Dynamic allocation allows a program to request memory while it is running rather than deciding the complete size at compile time.
The functions used include:
malloc: allocate a new block of memoryrealloc: resize an existing block of memoryfree: return allocated memory to the operating system
The declarations for these functions are provided by the standard library header:
#include <stdlib.h>Allocating with malloc
To allocate space for three integers:
int *list = malloc(3 * sizeof(int));This requests enough contiguous memory for three objects of type int.
The expression
calculates the number of bytes required. Using sizeof is safer than assuming that an integer always occupies a particular number of bytes.
malloc returns the address of the first byte in the allocated block. Therefore, the receiving variable must be a pointer:
int *list;Although the memory was obtained through a pointer, C permits array-style indexing:
list[0] = 1;
list[1] = 2;
list[2] = 3;This works because array indexing is syntactic sugar for pointer arithmetic. Conceptually:
list[i]is equivalent to:
*(list + i)The pointer is advanced by the size of the pointed-to type, not merely by one byte.
Checking for NULL
Dynamic allocation can fail if the computer does not have enough available memory. When allocation fails, malloc returns NULL.
A program should always check the result:
int *list = malloc(3 * sizeof(int));
if (list == NULL)
{
return 1;
}Dereferencing a NULL pointer can cause a segmentation fault.
Freeing memory
Every successful allocation should eventually be matched with a call to free:
free(list);Failing to free allocated memory creates a memory leak. A memory leak occurs when a program loses the pointer to allocated memory before releasing it.
When a short-lived program ends, the operating system normally reclaims its memory. However, this does not make leaks acceptable. Long-running programs can gradually consume more and more memory, causing:
Slower performance
Increased memory usage
Crashes
System instability
Tools such as Valgrind can help detect memory leaks.
Resizing Arrays with realloc
The function realloc can resize an existing allocation.
Conceptually, resizing an array from three integers to four requires:
bytes rather than:
A typical pattern is:
int *tmp = realloc(list, 4 * sizeof(int));
if (tmp == NULL)
{
free(list);
return 1;
}
list = tmp;Why a temporary pointer is necessary
It is dangerous to write:
list = realloc(list, 4 * sizeof(int));If realloc fails, it returns NULL, and the original allocation may still exist. Assigning NULL directly to list loses the address of the original block. The program can no longer free or use that memory, creating a leak.
Using a temporary pointer preserves the original address until the resize succeeds.
What realloc may do
realloc has two possible strategies:
Extend the existing block in place if sufficient contiguous memory exists immediately afterward.
Allocate a new block elsewhere, copy the old data into it, and release the old block.
The operating system or standard library tracks the size of existing allocations, so realloc knows how much old data must be preserved.
Even when realloc succeeds, resizing can still be expensive if the entire block must be moved and copied.
Defensive memory-management pattern
A robust dynamic-allocation process should:
Allocate memory.
Check whether the returned pointer is
NULL.Use the memory.
Resize through a temporary pointer when necessary.
Check the temporary pointer.
Free any memory that is no longer needed.
Free the final allocation before the program finishes.
Dynamic allocation improves flexibility, but it introduces additional code and opportunities for mistakes.
Linked Lists
A linked list stores elements in separate memory locations connected by pointers. Unlike an array, its elements do not need to be contiguous.
Suppose the values 1, 2, and 3 are stored at unrelated addresses:
The first node stores 1.
The second node stores 2 somewhere else.
The third node stores 3 somewhere else.
Because the nodes are not adjacent, the program cannot find the next node simply by adding a fixed number of bytes. Each node must explicitly store the address of the next node.
Nodes
A linked-list element is called a node. A node usually contains:
Data: the value the program wants to store
Metadata: information that helps organize or connect the data
For a list of integers, a node can be represented as:
typedef struct node
{
int number;
struct node *next;
}
node;The number field stores the actual data. The next field stores a pointer to the next node.
The final node’s next pointer is set to NULL, indicating the end of the list.
The list pointer
The list itself can be represented by a single pointer to the first node:
node *list = NULL;An empty list is therefore represented by a pointer containing NULL.
If the list contains nodes, the list pointer points to the first node. The first node points to the second, the second points to the third, and so on.
This creates a chain:
Creating a node
A new node can be allocated dynamically:
node *n = malloc(sizeof(node));The allocation must be checked:
if (n == NULL)
{
return 1;
}The node’s fields can then be initialized:
n->number = 1;
n->next = NULL;The arrow operator -> combines pointer dereferencing and structure-member access.
The expression:
n->numberis equivalent to:
(*n).numberThe arrow notation is easier to read and matches the conceptual picture of an arrow pointing to a structure.
Prepending a node
To insert a new node at the beginning of a list:
n->next = list;
list = n;The order is essential:
Make the new node point to the current first node.
Make the list pointer point to the new node.
If list is changed first, the program may lose the address of the old first node.
Example
If the list initially contains:
and a new node containing 2 is prepended:
Set the new node’s
nextfield tolist.Set
listto the new node.
The result is:
Repeatedly prepending values 1, 2, and 3 produces the order 3→2→1.
Traversing a linked list
To visit every node, a temporary pointer can move through the list:
for (node *ptr = list; ptr != NULL; ptr = ptr->next)
{
printf("%i\n", ptr->number);
}The loop performs the following operations:
Start at the first node.
Process the current node.
Move to the node stored in the current node’s
nextfield.Stop when the pointer becomes
NULL.
The temporary pointer does not create new nodes. It only provides a way to walk through the existing structure.
Freeing a linked list
free does not understand the structure of a linked list. It cannot be called once on the first node and expected to find all later nodes automatically.
Each node must be freed individually. However, the program must save the address of the next node before freeing the current node:
while (list != NULL)
{
node *tmp = list->next;
free(list);
list = tmp;
}The temporary pointer prevents the program from losing access to the remainder of the list.
Advantages of linked lists
Linked lists provide:
Dynamic growth
Dynamic shrinking
No need for contiguous free memory
No need to copy all existing elements when adding a node
Efficient insertion at a known position, especially at the beginning
A new node can be placed anywhere in memory, provided its pointers are updated correctly.
Disadvantages of linked lists
Linked lists also require:
Extra memory for pointers
More complicated code
Careful memory management
Traversal to locate elements
No direct random access by index
A linked list cannot jump directly to its middle or to an arbitrary element. It must follow pointers from the beginning.
Linked-List Operation Complexity
The complexity of a linked-list operation depends on how the list is implemented.
Insertion at the beginning
Prepending requires only a fixed number of pointer assignments:
The time does not depend on the number of existing nodes.
Insertion at the end
If the program has only a pointer to the beginning, appending requires traversing the entire list to find the final node:
A separate pointer to the last node could make appending constant time, but that pointer must be maintained correctly.
Searching
Searching for a value may require checking every node:
The worst case occurs when the desired value is at the end or is not present.
Even if the list is sorted, a standard singly linked list does not support efficient binary search because the program cannot jump directly to the middle.
Traversal
Printing or processing every node requires visiting all n nodes:
Deletion
Deleting a node generally requires finding it first, and possibly finding the node before it so the links can be repaired:
Linked lists therefore trade the resizing cost of arrays for slower searching and additional pointer storage.
Arrays Versus Linked Lists
Arrays
Contiguous memory
Fast indexed access
Efficient binary search when sorted
Fixed or difficult-to-change size
May require copying during resizing
Less memory per element
Linked lists
Noncontiguous memory
Flexible size
No need to move existing nodes during growth
Slow searching and traversal
Extra pointer per node
More complicated insertion and deletion logic
Neither structure is universally superior. The appropriate choice depends on whether the application values:
Fast searching
Efficient memory use
Dynamic resizing
Simpler implementation
Fast insertion or deletion
Trees
A tree is a hierarchical data structure. It introduces a second dimension compared with an array or ordinary linked list.
A tree contains:
A root, the topmost node
Children, nodes connected below another node
Parents, nodes connected above other nodes
Leaves, nodes with no children
A linked list can be viewed as a structure in which each node has at most one child. A tree allows a node to have multiple children.
Binary Search Trees
A binary search tree, or BST, is a tree in which each node has at most two children:
A left child
A right child
The defining ordering property is:
Values in the left subtree are smaller than the node’s value, and values in the right subtree are larger than the node’s value.
This property applies recursively to every subtree.
For example:
The node containing 2 must itself have smaller values to its left and larger values to its right. The same rule applies to the node containing 6.
Recursive structure
A BST is recursive because each child is itself the root of a smaller tree.
For any node:
Its left child identifies a smaller BST.
Its right child identifies another smaller BST.
Each subtree follows the same ordering rule.
This recursive property makes recursive search code natural.
BST node structure
A node in a linked list contains one data field and one pointer. A BST node needs one data field and two pointers:
typedef struct node
{
int number;
struct node *left;
struct node *right;
}
node;The additional pointers allow the node to connect to two subtrees.
Searching a binary search tree
A recursive search algorithm can be described as follows:
If the tree pointer is
NULL, the value is absent.If the target is smaller than the current node, search the left subtree.
If the target is larger than the current node, search the right subtree.
Otherwise, the target matches the current node.
In C-like pseudocode:
bool search(node *tree, int number)
{
if (tree == NULL)
{
return false;
}
else if (number < tree->number)
{
return search(tree->left, number);
}
else if (number > tree->number)
{
return search(tree->right, number);
}
else
{
return true;
}
}At each node, the algorithm eliminates an entire subtree from consideration. If the target is greater than the current value, the left subtree can be ignored. If the target is smaller, the right subtree can be ignored.
Balanced BST complexity
If the tree is balanced, each decision approximately halves the remaining search space. The height is approximately:
Therefore, searching, inserting, and deleting can each take approximately:
when the tree remains balanced.
A balanced tree with seven nodes, for example, has a height of approximately:
which is close to two levels beyond the root.
The danger of an unbalanced tree
The order in which values are inserted affects the shape of a naïve BST.
Inserting:
creates a balanced structure:
However, inserting:
creates a one-sided structure:
The tree has effectively degenerated into a linked list. Its height becomes proportional to n, so searching becomes:
A balanced tree avoids this problem by rearranging or rotating nodes after insertions and deletions. Such balancing requires additional algorithmic work but preserves logarithmic performance.
BST trade-offs
Binary search trees provide:
Dynamic growth and shrinking
Faster search than an ordinary linked list when balanced
No need for contiguous memory
The ability to maintain sorted order
They require:
Two pointers per node
More memory than a linked list
More complicated insertion and deletion
Balancing if reliable O(logn) performance is required
Hashing
Hashing maps an input from a potentially very large or infinite domain to a finite range of output values.
In mathematical terms:
The output identifies a location called a bucket.
Hash functions
A hash function receives a key and produces a bucket index.
For names, a simple hash function could use the first letter:
Names beginning with
Ago to bucket 0.Names beginning with
Bgo to bucket 1.Names beginning with
Cgo to bucket 2.Names beginning with
Mgo to bucket 12.Names beginning with
Zgo to bucket 25.
Because C uses zero-based indexing, the letter M, which is the thirteenth letter of the alphabet, maps to index 12.
A C implementation could convert the first letter to uppercase and subtract the ASCII value of uppercase A:
return toupper(name[0]) - 'A';This produces a value from 0 through 25, assuming the input begins with an English alphabetic character.
Hash-function design considerations
A useful hash function should:
Produce valid bucket indices
Avoid negative results
Distribute values as evenly as possible
Reduce the number of collisions
Be efficient to compute
A parameter such as const can prevent a function from modifying an input string that it receives through a pointer.
An unsigned integer type can express the fact that a bucket index should not be negative.
Hash Tables
A hash table combines an array with one or more linked lists.
It is commonly used to implement dictionaries, which store key-value pairs:
A dictionary stores words and definitions.
A phone book stores names and phone numbers.
A hash table stores keys and associated values.
Structure of a hash table
A hash table may contain an array of 26 linked-list pointers:
node *table[26];Each array position represents a bucket. Each bucket points to the first node in a linked list.
For example:
Bucket 0 contains names beginning with
A.Bucket 1 contains names beginning with
B.Bucket 12 contains names beginning with
M.Bucket 25 contains names beginning with
Z.
A node might contain:
typedef struct node
{
char *name;
struct node *next;
}
node;The hash table therefore has this conceptual form:
Collisions
A collision occurs when multiple keys map to the same bucket.
For example, the names Mario, Marth, and Mega Man may all map to the bucket for M.
A collision is unavoidable when a large domain is mapped to a smaller finite range. The hash function must place many possible inputs into a limited number of buckets.
Separate chaining handles collisions by storing multiple values in a linked list within the same bucket.
Searching a hash table
Searching involves two stages:
Apply the hash function to determine the correct bucket.
Search the linked list in that bucket.
If names are distributed evenly across k buckets, each linked list contains approximately:
elements.
For an alphabet-based table with 26 buckets, the expected list length may be approximately:
This is much faster in practice than searching one linked list containing all n values. However, in asymptotic notation, if k is treated as a fixed constant:
The constant factor can be very beneficial, even though the formal Big-O category remains linear.
Improving the hash function
A hash function based only on the first character may cause many collisions. A more selective function could use the first three characters.
For example:
LIN...could map to a bucket for Link.LUI...could map to a bucket for Luigi.Other three-letter combinations could receive their own buckets.
Using more characters reduces collisions, but it dramatically increases the number of possible buckets.
If there are 26 possible letters and three positions are used, the theoretical number of combinations is:
Many combinations may never occur, which means much of the allocated table could remain unused.
Hash-table trade-offs
Hash tables provide:
Fast average-case lookup
Convenient key-value association
Dynamic linked-list storage within buckets
A flexible general-purpose structure
They require:
A good hash function
Collision handling
Additional memory for buckets and pointers
More memory if collisions are reduced by creating many buckets
The practical performance depends heavily on how evenly keys are distributed.
Tries
A trie is a tree-like structure made from arrays. The name comes from “retrieval.”
A trie is especially useful for storing strings such as:
Names
Words
Prefixes
Autocomplete entries
Dictionary terms
Trie structure
Each trie node contains an array of pointers, one for each possible next character.
For English letters, each node may contain:
child pointers corresponding to A through Z.
Each pointer leads to another node representing the next character in a word.
A node may also contain:
A Boolean indicating whether a complete word ends there
A value associated with the word, such as a phone number
Storing a word
To store TOAD:
Start at the root.
Follow the pointer for
T.From that node, follow the pointer for
O.From there, follow the pointer for
A.From there, follow the pointer for
D.Mark the final node as representing the end of a complete word.
The word itself does not necessarily need to be stored as a complete character array. Its path through the trie implicitly represents the word.
A trie can store words where one is a prefix of another. For example, TOAD and TOADETTE can share the nodes for TOAD, then continue along different paths.
Searching a trie
To search for TOAD:
Begin at the root.
Follow the pointer for
T.Follow the pointer for
O.Follow the pointer for
A.Follow the pointer for
D.Check whether the final node marks the end of a stored word.
If any required pointer is NULL, the word is absent.
Trie complexity
The search time depends on the length of the key rather than the number of stored keys.
If the maximum key length is bounded by a fixed constant L, searching takes:
When L is treated as fixed, this is often described as:
Thus, whether the trie stores three names or three million names, searching for a name of bounded length requires following only a bounded number of character links.
Trie trade-offs
Tries provide:
Very fast lookup
Natural prefix searching
No collision problem in the same sense as hash tables
Efficient storage of relationships among strings
They require:
Many pointers per node
Considerable memory
Potentially large amounts of unused space
More complicated implementation
A trie node with 26 child pointers can consume substantial memory even when most of those pointers are NULL.
Overall Trade-offs
The major structures can be viewed as different compromises.
Array
Strength: fast indexed access and binary search
Weakness: fixed or difficult-to-resize capacity
Typical search: O(logn) if sorted
Linked list
Strength: flexible growth and shrinking
Weakness: sequential access and extra pointer storage
Typical search: O(n)
Balanced binary search tree
Strength: dynamic structure with ordered search
Weakness: extra pointers and balancing complexity
Typical search: O(logn)
Hash table
Strength: fast average-case key lookup
Weakness: collisions and memory overhead
Typical lookup: approximately constant time in favorable conditions, though poor distributions can lead to O(n)
Trie
Strength: lookup based primarily on key length
Weakness: very high memory usage
Typical lookup: O(L), often treated as O(1) for bounded key length
The best structure depends on the most important resource or requirement:
Time: choose structures that minimize search or insertion steps.
Memory: choose structures with fewer pointers and less unused space.
Flexibility: choose structures that grow and shrink dynamically.
Ordering: choose arrays or search trees when sorted data matters.
Key-value lookup: choose hash tables or tries.
Prefix queries: choose tries.
Data structures are not universally “best.” Their value depends on the operations required and the trade-offs acceptable for the application.

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