Stacks and Queues


Stacks and Queues

Anna
Welcome back to CS50. This is week five, and today we're focusing on data structures. It is also our last week working in C before we transition to Python, a higher-level language that will let us solve many of the same problems more quickly as humans, even though the resulting code may not always run as quickly as equivalent C code.

Maria
So the big theme connecting C and Python is trade-offs. We may gain convenience and speed as programmers, but sometimes give up performance when the computer runs the code. Today, those trade-offs will appear in space, time, flexibility, and ease of implementation.

Anna
Let's begin with two data structures we encounter in everyday life: queues and stacks. Think of Jack, who stored all his clothes, books, and CDs in one pile. He always took the item from the top, washed it, and put it back on top, so he kept choosing the same few items.

Maria
Lou's solution was to use a queue-like arrangement instead. Jack put clothes away at one end and took them from the other, so he would eventually wear everything before repeating an item. These examples illustrate abstract data types: the important idea is the behavior and operations they provide, not the particular low-level way they are implemented.

Anna
A queue follows the FIFO property: first in, first out. The person who joins the line first should be served first, while the person who arrives last waits at the end. The two fundamental queue operations are enqueue, meaning add something to the back, and dequeue, meaning remove something from the front.

Maria
One simple C implementation gives a queue a fixed capacity, perhaps fifty people. The structure contains an array of fifty people and a size field recording how many people are currently in the queue. Capacity tells us the maximum possible size; size tells us how many spaces are actually occupied right now.

Anna
The obvious limitation is that a fifty-person queue cannot remember a fifty-first person. We could recompile the program with a larger capacity, but then we face a trade-off. If we allocate too little memory, the structure is inadequate; if we allocate far too much, we waste memory, and the computer has only a finite amount available.

Maria
A fixed array also requires us to track where the front of the queue is as people are removed. Ideally, we would like a queue that grows when needed and shrinks when memory is no longer needed, asking the operating system for memory dynamically rather than deciding everything at compile time.

Anna
A stack has the opposite ordering rule: LIFO, or last in, first out. If we place sweaters on top of one another, the sweater we added most recently is the easiest one to remove. The same idea appears in cafeteria trays, where new trays are placed on top and people take the top tray.

Maria
Stacks are also common in software interfaces. New email often appears at the top of an inbox, and people tend to focus on the newest messages first. The two basic stack operations are push, which adds an item to the top, and pop, which removes an item from the top.

Anna
A stack can use almost the same structure as the fixed queue: an array and a size field. The difference is how we interpret the available positions and perform the operations. But the fixed-capacity limitation remains. Even a stack implemented with an array of fifty positions can hold only fifty items unless we resize it.

Maria
That leads us to dictionaries, another abstract data type. A dictionary associates one piece of data with another: a word with its definition, a person's name with a phone number, or more generally a key with a value. Dictionaries are everywhere in computing, but they too can be implemented in multiple ways, with different limits and running times.

Anna
Before building more sophisticated structures, recall what an array is: a contiguous chunk of memory whose values are stored back to back. In C, an array such as an integer array of size three is normally given its size in advance. Its positions are zero-indexed, so three values occupy locations zero, one, and two.

Maria
If we later need a fourth value, a fixed array does not automatically provide an extra position. We can allocate a larger region, copy the old values into it, add the new value, and give the old region back to the operating system. But copying becomes expensive when the array contains millions of values.

Anna
C lets us allocate memory dynamically with malloc. Instead of declaring an array of a fixed size, we can request enough space for three integers using three times sizeof int. malloc returns the address of the allocated memory, which we can store in an int pointer.

Maria
Because pointers and arrays are closely related in C, we can use square-bracket notation with that dynamically allocated memory. Writing list at index zero, one, or two is equivalent to pointer arithmetic and dereferencing, but it is much more readable.

Anna
If we need more space while the program is running, we could allocate a new region temporarily, copy the old values into it with a loop, add the new value, free the old region, and then make the main pointer refer to the new region. The temporary pointer matters because assigning a new malloc result directly to the original pointer would lose the address of the old memory and create a memory leak.

Maria
Whenever we use malloc, we should check whether it returned NULL, which indicates that allocation failed. We should also free every region we allocate. If a later allocation fails, we should still free any earlier memory before returning an error, even though the operating system ultimately reclaims memory when a program exits.

Anna
The realloc function can simplify resizing. It receives the address of the existing allocation and the new requested size. If possible, it grows the existing region; otherwise, it allocates a new region, copies the old data, and returns the new address. We still use a temporary pointer, because if realloc fails and returns NULL, the original allocation remains valid and we must not lose its address.

Maria
Now we can move beyond arrays. The goal of a linked list is to use memory wherever it is available instead of requiring all values to be contiguous. Each element, or node, contains the data we care about and metadata that helps us find the next element.

Anna
For example, a node might contain an integer and a pointer to the next node. The final node's next pointer is NULL, marking the end. A separate pointer called list stores the address of the first node, because from the first node we can follow pointers through the entire structure.

Maria
In C, the node can be defined with a struct. It contains an int number and a pointer of type struct node star called next. The arrow operator combines dereferencing a pointer and accessing a structure field, so n arrow number means: go to the node pointed to by n and access its number field.

Anna
To build a list, we can start with list equal to NULL. Then, repeatedly, we allocate a new node, check that allocation succeeded, obtain a number from the user, initialize the node's next pointer, and connect the node to the existing list.

Maria
The simplest connection strategy is prepending. Set the new node's next pointer equal to list, then set list equal to the new node. This preserves every existing node, because the new node points to the old first node before list is updated.

Anna
If we prepend the values one, two, and three, the final list is three, two, one. That is perfectly valid, but it is reverse order. To print the list, we use another temporary pointer. Start it at list, print the current node's number, move it to the current node's next pointer, and continue until the pointer is NULL.

Maria
That traversal can be written with a while loop or a for loop. The temporary traversal pointer is different from the pointer used while allocating nodes, because each variable has a separate role. Temporary pointers used for traversal or construction can disappear, while the linked list itself remains in memory as long as its nodes are connected.

Anna
Linked lists use more memory than a plain array because every value needs an additional pointer. That is an intentional trade-off. We spend extra space to gain the ability to grow and shrink without copying all existing values to a new contiguous region.

Maria
If we always prepend, insertion takes big O of one: a constant number of pointer updates, regardless of how long the list is. But searching takes big O of n in the worst case, because the desired value may be at the end. Traversing and deleting also take big O of n when we may need to examine the whole list.

Anna
Appending to the end has a different cost. Without an additional pointer to the final node, we must traverse the list to find its end, so insertion is big O of n. We could maintain another pointer to the end, but that uses additional space and requires keeping that pointer up to date.

Maria
Maintaining sorted order is more involved. A new node might belong in an empty list, at the beginning, at the end, or somewhere in the middle. Breaking the problem into those four cases makes the code manageable, but pointer order matters: if we update the wrong pointer first, we can orphan nodes and leak memory.

Anna
At the end, freeing a linked list requires visiting and freeing every node individually. free is not aware that your nodes form a linked list, so you cannot pass it only the first node and expect the rest to disappear. You need to preserve a pointer to the next node, free the current node, and then continue.

Maria
A linked list gives us dynamic growth, but it loses the fast random access and binary search that arrays provide. In an array, the computer can jump directly to the middle using arithmetic. In a linked list, the computer cannot calculate where the middle node is, because the nodes may be scattered throughout memory and connected only by pointers.

Anna
A doubly linked list adds a pointer in both directions. That can make insertion and deletion code easier in some situations, because each node knows both its predecessor and successor. But it does not fundamentally change the asymptotic running time; searching can still be big O of n.

Maria
Trees combine some of the ideas from arrays and linked lists. A tree adds a second dimension: instead of every node having only one next pointer, a binary search tree can have a left child and a right child. Its top node is called the root, and nodes without children are called leaves.

Anna
A binary search tree is not just any tree of numbers. For every node, values in the left subtree are smaller and values in the right subtree are larger, assuming no duplicate values. This property is recursive because it applies not only to the whole tree but also to every smaller subtree.

Maria
That ordering lets us search efficiently. Start at the root. If the target is smaller, follow the left pointer; if it is larger, follow the right pointer; if it matches the current node, we are done. At every step, we discard one of the two subtrees.

Anna
The recursive search function has a simple base case: if the tree pointer is NULL, the value is not present, so return false. Otherwise, recursively search the left or right child depending on the comparison, or return true if the current number matches the target.

Maria
If the tree stays balanced, its height is approximately log base two of n, so searching, inserting, and deleting can be big O of log n. The trade-off is space: each node stores a value and two pointers, rather than just the value in an array.

Anna
But a binary search tree can become unbalanced. If values arrive in increasing order, such as one, two, three, four, and five, each new value follows the right branch, and the supposed tree degenerates into something that looks like a linked list. In that worst case, operations become big O of n again.

Maria
Some tree designs rebalance themselves after insertions or deletions. That costs additional work, but it prevents the structure from becoming a long chain. The broader lesson is that a data structure's performance depends not only on its definition, but also on the details of its implementation and the input it receives.

Anna
The ideal goal is constant-time access, or big O of one: a number of steps that does not grow with the amount of data. Hashing helps us move toward that goal by mapping a potentially very large domain of inputs to a finite range of output locations, which we can call buckets.

Maria
A hash function performs that mapping. For example, to organize names, a simple function could examine the first letter, convert it to uppercase, and subtract the character code for capital A. The name beginning with A maps to bucket zero, B to bucket one, and M to bucket twelve.

Anna
A hash table uses an array of buckets, often with a linked list in each bucket. If we have twenty-six buckets, the first letter determines the array position. The name itself, or the associated data such as a phone number, is stored in a node connected to that bucket.

Maria
The problem is collisions. Mario and multiple other names beginning with M all map to the same bucket. Instead of overwriting one another, the names can be connected in a linked list within that bucket. This is why a hash table is an array of linked lists.

Anna
With a reasonably uniform distribution of names, each linked list is much shorter than one giant list. If there are n names and k buckets, a typical bucket might contain about n divided by k names. That is faster in practice, but in big O notation the division by a constant k does not change the asymptotic classification, so the worst-case expression remains big O of n.

Maria
A more detailed hash function could use the first three letters instead of only the first letter. That reduces collisions, because names such as Link and Luigi are less likely to share the same three-letter prefix. But it requires many more buckets, including combinations that may never be used, so the cost is a large amount of wasted memory.

Anna
This is the central hash-table trade-off: a better hash function can make searches faster by reducing collisions, but it can also consume more memory. A poor hash function creates long linked lists; an overly elaborate one may allocate far more buckets than the data requires.

Maria
A trie pushes the goal of constant-time lookup further. A trie is a tree made from arrays. Each node contains an array of pointers, one for every possible letter, and a path through those pointers represents the successive letters of a word.

Anna
To insert the word Toad, we follow the T position in the root array, then the O position in the next node, then A, then D. A Boolean or similar marker indicates that a complete word ends at the D node. The word is represented by the path, rather than necessarily being stored as one explicit string.

Maria
A trie can store words where one is a prefix of another. For example, Toad and Toadette can share the path for Toad, while a marker identifies the end of Toad and additional nodes continue the path for Toadette. Other names can reuse any shared prefixes.

Anna
To search for Toad, follow the four character pointers and inspect the marker at the end. The number of steps depends on the word's length, not on how many total words are stored. If the maximum relevant word length is treated as bounded, lookup is effectively constant time.

Maria
The trade-off is substantial memory usage. Every trie node can contain an array of twenty-six pointers, and most of those pointers may be NULL and unused. Tries can offer extremely fast lookup, but hash tables often provide a more practical balance between time and space.

Anna
These ideas appear outside textbooks. At restaurants such as Sweetgreen, pickup salads can be placed into shelves according to name ranges. That is essentially a real-world hashing system: the name determines a bucket, and the order is stored within that bucket.

Maria
But that system can also experience collisions and capacity problems. Some name ranges may fill up while others remain nearly empty. A practical redesign can combine ranges or make certain buckets larger, showing once again that real systems must balance available space, expected input, and speed.

Anna
So today's progression was deliberate: arrays are simple and fast but fixed in size; linked lists grow dynamically but require linear searching; trees can restore logarithmic search when balanced; hash tables use buckets and linked lists to reduce search time; and tries can provide extremely fast lookup at a much higher memory cost.

Maria
And the same trade-off applies to stacks, queues, and dictionaries. These are abstract data types defined by the behavior they offer, while arrays, linked lists, trees, hash tables, and tries are concrete ways to implement that behavior.

Anna
For the upcoming problem set, the focus will include implementing a hash table for a spell checker. The program will load more than one hundred thousand English words, and its performance can be evaluated by both how quickly it runs and how much memory it uses.

Maria
That makes the lesson practical: choosing a data structure is not about finding one universally best answer. It is about deciding which trade-off matters most for the problem—memory, running time, flexibility, fairness, or implementation complexity.

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