Stacks and Queues
- 83Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is the main trade-off between using a lower-level language such as C and a higher-level language such as Python?
83 questions
- 1
What is the main trade-off between using a lower-level language such as C and a higher-level language such as Python?
Model answer
Higher-level languages generally let humans solve problems more quickly, while lower-level languages may produce code that runs more efficiently on the computer.
Explanation
The trade-off involves programmer convenience and development speed versus possible execution speed and lower-level control.
- 2
What is an abstract data type?
Model answer
An abstract data type is defined by the operations and behavior it provides rather than by the specific implementation used to build it.
Explanation
Stacks, queues, and dictionaries can each be implemented in multiple ways while preserving their essential behavior.
- 3
Why can the same abstract data type have different real-world performance characteristics?
Model answer
Different implementations use memory and perform operations differently, so they can have different limits, speeds, and resource requirements.
Explanation
For example, a queue can be implemented with a fixed-size array or with dynamically allocated linked nodes.
- 4
What is a dictionary as an abstract data type?
Model answer
A dictionary stores associations between keys and values, such as words and definitions or names and phone numbers.
Explanation
The key identifies the information, while the associated value is the data retrieved using that key.
- 5
What is an array?
Model answer
An array is a contiguous region of memory containing values stored back to back.
Explanation
Because its elements are contiguous, an array supports direct indexing and arithmetic-based access.
- 6
Why are arrays well suited to binary search?
Model answer
Their contiguous layout allows a program to calculate the location of the middle element and repeatedly divide the search range.
Explanation
This makes binary search possible in logarithmic time when the array is sorted.
- 7
What is the main limitation of a statically sized array?
Model answer
Its capacity must be chosen in advance, so it may be too small for the data or waste memory if it is overallocated.
Explanation
A fixed array cannot automatically grow when more values need to be stored.
- 8
What is the purpose of the
structkeyword in C?Model answer
The
structkeyword defines a custom data structure containing related fields.Explanation
Structures are used to create nodes and other objects that combine data with metadata such as pointers.
- 9
What does the dot operator do when working with a structure in C?
Model answer
The dot operator accesses a field within a structure value.
Explanation
For example, it can be used to access a person's name or a node's number.
- 10
What does the arrow operator do in C?
Model answer
The arrow operator accesses a field through a pointer to a structure.
Explanation
The expression
pointer->fieldis equivalent to dereferencing the pointer and then using the dot operator. - 11
What does FIFO mean, and which data structure uses this property?
Model answer
FIFO means first in, first out; it is the defining ordering property of a queue.
Explanation
The first item added to a queue is the first item removed, which supports fairness in lines.
- 12
What are the two fundamental operations on a queue?
Model answer
The operations are enqueue, which adds an item to the queue, and dequeue, which removes an item from the front.
Explanation
Enqueue corresponds to joining the line, while dequeue corresponds to leaving from the front.
- 13
Why is FIFO useful for a real-world line?
Model answer
FIFO provides fairness because people who arrive first are served before people who arrive later.
Explanation
A queue at a store or event normally serves people in their order of arrival.
- 14
What is LIFO, and which data structure uses this property?
Model answer
LIFO means last in, first out; it is the defining ordering property of a stack.
Explanation
The most recently added item is the first item removed from the top.
- 15
What are the two fundamental operations on a stack?
Model answer
The operations are push, which adds an item to the top, and pop, which removes an item from the top.
Explanation
Both operations take place at the same end of the stack.
- 16
Why are stacks useful for trays or clothing?
Model answer
Items can be added and removed efficiently from the top without disturbing the rest of the stack.
Explanation
Gravity naturally supports taking the top tray, even though older items at the bottom may be neglected.
- 17
How can a stack be implemented using an array?
Model answer
A stack can use an array to store its items and a size field to identify the current top or number of stored items.
Explanation
Removing from the end of the array avoids shifting the other elements.
- 18
What limitation do array-based stacks and queues share?
Model answer
They have a fixed capacity unless the program allocates a larger region and transfers the existing elements.
Explanation
A fixed array cannot hold more items than the number of positions allocated for it.
- 19
How do capacity and size differ in an array-based queue?
Model answer
Capacity is the maximum number of items the structure can hold, while size is the number of items currently stored.
Explanation
Tracking both values identifies which array positions are occupied or available.
- 20
Why might a fixed-size queue waste memory?
Model answer
If the queue is allocated for many possible items but only a few arrive, the unused positions still consume memory.
Explanation
Overallocating prevents overflow but wastes finite memory resources.
- 21
What is the purpose of
mallocin C?Model answer
mallocrequests a specified number of bytes from the operating system and returns the address of the allocated memory.Explanation
It allows a program to allocate memory dynamically while it is running.
- 22
Why is
sizeofused withmalloc?Model answer
sizeofdetermines the number of bytes required for a particular type, allowing the program to allocate the correct amount of memory.Explanation
For example, allocating space for several integers uses the number of integers multiplied by
sizeof(int). - 23
How can dynamically allocated memory be used like an array in C?
Model answer
A pointer to the allocated block can be indexed with square brackets because C treats pointer indexing as equivalent to pointer arithmetic.
Explanation
An expression such as
list[i]accesses the element at the appropriate offset from the beginning of the block. - 24
What does it mean to resize a dynamically allocated array?
Model answer
Resizing means obtaining a larger or smaller memory region and preserving the data that should remain in the new region.
Explanation
If the original block cannot grow in place, its contents must be copied to another block.
- 25
Why is assigning a new
mallocresult directly to an existing pointer dangerous?Model answer
It can overwrite the only pointer to the old block, causing a memory leak because the old block can no longer be freed.
Explanation
The original address must be preserved until its contents are copied and the block is released.
- 26
Why is a temporary pointer useful when reallocating memory manually?
Model answer
It preserves the address of the new block while the original pointer still identifies the old block.
Explanation
This allows the program to copy the old data, free the old block, and then update the main pointer safely.
- 27
What must a program check after calling
mallocorrealloc?Model answer
It must check whether the returned pointer is
NULL, which indicates that the allocation failed.Explanation
Using a failed allocation as if it were valid memory can cause a segmentation fault.
- 28
What should a program do if a later allocation fails after an earlier allocation succeeded?
Model answer
It should free the earlier allocated memory before returning an error.
Explanation
This prevents a memory leak during the error-handling path.
- 29
What does
freedo?Model answer
freereturns dynamically allocated memory to the operating system so that it can be reused.Explanation
Every successfully allocated block should eventually be freed when it is no longer needed.
- 30
Why can memory leaks still matter even though the operating system reclaims memory when a program exits?
Model answer
Programs often run for a long time, so leaked memory can accumulate and slow down or destabilize the program before it exits.
Explanation
Short programs may hide leaks, but long-running software must release unused memory during execution.
- 31
What advantage does
reallocprovide over manually allocating and copying a larger array?Model answer
reallocattempts to expand the existing block in place and otherwise allocates a new block and copies the old data automatically.Explanation
It reduces the amount of manual copying code needed when resizing memory.
- 32
Why should a temporary pointer still be used with
realloc?Model answer
If
reallocfails and returnsNULL, assigning that result directly would lose the original pointer even though the original block remains valid.Explanation
A temporary pointer preserves access to the original block until reallocation succeeds.
- 33
What is a node in a linked data structure?
Model answer
A node is a structure containing the data of interest and metadata, usually one or more pointers to related nodes.
Explanation
The metadata connects separately allocated memory blocks into a larger data structure.
- 34
What is a linked list?
Model answer
A linked list is a sequence of nodes connected by pointers, allowing the nodes to be located anywhere in memory.
Explanation
Unlike an array, a linked list does not require its data elements to be contiguous.
- 35
How does a linked list make use of fragmented memory?
Model answer
It allocates individual nodes wherever sufficient memory is available and connects them with pointers.
Explanation
The nodes do not need to occupy one large contiguous region.
- 36
What does the
nextpointer in a singly linked list represent?Model answer
The
nextpointer stores the address of the following node in the list.Explanation
Following these pointers lets the program traverse the list from one node to the next.
- 37
How is an empty linked list represented?
Model answer
An empty linked list is represented by a list pointer whose value is
NULL.Explanation
A null pointer indicates that there is no first node.
- 38
What does the list pointer in a linked list identify?
Model answer
The list pointer stores the address of the first node in the list.
Explanation
The first node leads to the second, and so on, through its
nextpointers. - 39
How is a new node prepended to a linked list?
Model answer
Set the new node's
nextpointer to the current list pointer, then update the list pointer to the new node.Explanation
These two assignments preserve the existing list while placing the new node at the front.
- 40
Why must a new node's
nextpointer be assigned before updating the list pointer when prepending?Model answer
The new node must first point to the existing list so that updating the list pointer does not lose access to the old nodes.
Explanation
Changing the list pointer first without linking the new node could orphan the existing list.
- 41
What order do values appear when nodes are repeatedly prepended?
Model answer
They appear in reverse order from the order in which they were inserted.
Explanation
Each new value becomes the first node, so the most recently inserted value is encountered first.
- 42
How can a linked list be traversed?
Model answer
Start a temporary pointer at the first node and repeatedly follow its
nextpointer until the pointer becomesNULL.Explanation
The traversal visits each node exactly once when processing the list sequentially.
- 43
Why should a separate traversal pointer be used instead of changing the list pointer?
Model answer
The list pointer must continue to identify the first node, while the temporary pointer moves through the list.
Explanation
Overwriting the list pointer during traversal could lose the entry point needed to access or free the list.
- 44
How does a linked list differ from an array in memory layout?
Model answer
An array stores values contiguously, whereas a linked list stores nodes that may be separated throughout memory and connects them with pointers.
Explanation
This gives linked lists flexibility in memory use but adds pointer overhead.
- 45
What is the main advantage of inserting at the beginning of a linked list?
Model answer
Insertion at the beginning takes constant time because it changes only a fixed number of pointers.
Explanation
The operation does not depend on how many nodes are already in the list.
- 46
What is the running time of searching an unspecialized linked list?
Model answer
Searching takes O(n) time in the worst case because the desired value may be at the end or absent.
Explanation
A linked list generally must be traversed node by node.
- 47
What is the running time of traversing a linked list?
Model answer
Traversing a linked list takes O(n) time because every one of the n nodes must be visited.
Explanation
Printing or processing every element necessarily requires touching every node.
- 48
Why does appending to a linked list take O(n) time without an end pointer?
Model answer
The program must follow the list from the beginning to find the final node.
Explanation
Maintaining a separate pointer to the last node can make appending constant time, at the cost of extra bookkeeping.
- 49
What are the four cases to consider when inserting into a sorted linked list?
Model answer
The new node may be inserted into an empty list, at the beginning, at the end, or somewhere in the middle.
Explanation
Separating these cases makes the pointer updates easier to design and verify.
- 50
Why must pointer-update order be handled carefully when inserting into the middle of a linked list?
Model answer
Updating a pointer in the wrong order can disconnect or orphan part of the list.
Explanation
The existing neighboring nodes must remain reachable while the new node is linked between them.
- 51
How should a linked list be freed?
Model answer
Traverse the list while saving the next node, free the current node, and then continue with the saved pointer.
Explanation
The next pointer must be saved before freeing the current node because its contents are no longer available afterward.
- 52
What is a doubly linked list?
Model answer
A doubly linked list is a linked list in which each node has pointers to both the next node and the previous node.
Explanation
The additional backward pointer can simplify some insertion, deletion, and traversal operations.
- 53
What is the main trade-off of adding pointers to linked-list nodes?
Model answer
The pointers allow flexible growth and connection of nodes but consume additional memory.
Explanation
Linked structures exchange space for dynamism and, in some cases, simpler insertion.
- 54
What is a binary tree?
Model answer
A binary tree is a tree data structure in which each node can have up to two child nodes.
Explanation
The two children are commonly called the left child and the right child.
- 55
What is the root of a tree?
Model answer
The root is the topmost node from which the rest of the tree can be reached.
Explanation
It serves as the starting point for traversing or searching the tree.
- 56
What is a leaf node?
Model answer
A leaf node is a node with no children.
Explanation
Leaf nodes occur at the outer edges of a tree.
- 57
What property defines a binary search tree?
Model answer
Each node's values in the left subtree are smaller and each value in the right subtree is larger, assuming no duplicate values.
Explanation
This ordering property allows the search to eliminate one subtree at each comparison.
- 58
Why is a binary search tree considered recursive?
Model answer
Each node and its descendants form smaller binary search trees that obey the same ordering rule.
Explanation
The entire structure can be defined in terms of a root and its left and right subtrees.
- 59
How does searching a binary search tree eliminate work?
Model answer
At each node, the comparison determines whether to continue in the left subtree, the right subtree, or stop because the value was found.
Explanation
The ordering property makes the other subtree irrelevant for that search.
- 60
What is the search time for a balanced binary search tree?
Model answer
Searching takes O(logn) time because the tree's height grows logarithmically when each level roughly doubles the number of nodes.
Explanation
Each comparison removes approximately half of the remaining possibilities.
- 61
What are the typical search, insertion, and deletion times in a balanced binary search tree?
Model answer
Each operation can take approximately O(logn) time.
Explanation
Each operation follows a path whose length is bounded by the tree's logarithmic height.
- 62
How can a binary search tree become inefficient?
Model answer
If values are inserted in an unfavorable order, the tree can become unbalanced and degenerate into a structure resembling a linked list.
Explanation
In that case, the height becomes proportional to n instead of logn.
- 63
What is the running time of searching an unbalanced binary search tree in the worst case?
Model answer
The worst-case running time is O(n).
Explanation
A completely unbalanced tree may require visiting nodes one at a time along a single long path.
- 64
How can balanced-tree algorithms prevent a binary search tree from degenerating?
Model answer
They rearrange or rotate nodes after insertions or deletions to keep the tree's height approximately logarithmic.
Explanation
Rebalancing costs additional work but preserves efficient operations.
- 65
What fields does a binary search tree node typically contain?
Model answer
It contains the stored value, a pointer to the left child, and a pointer to the right child.
Explanation
The two child pointers provide the tree's branching structure.
- 66
What are the base and recursive cases in a recursive binary-search-tree search?
Model answer
The base cases are an empty tree, which returns false, and a matching value, which returns true; otherwise the function recursively searches the appropriate child.
Explanation
The comparison reduces the problem to a smaller subtree until the value is found or no subtree remains.
- 67
What is hashing?
Model answer
Hashing maps values from a potentially large or infinite domain to a finite range of positions or buckets.
Explanation
The resulting position helps organize data for faster retrieval.
- 68
What is a hash function?
Model answer
A hash function takes an input key and computes the bucket or index where that key should be stored.
Explanation
For example, a function can map a name to an index based on its first letter.
- 69
How could a simple hash function map English names to array positions?
Model answer
It could convert the first letter to uppercase and subtract the character code for
A, producing an index from 0 through 25.Explanation
Names beginning with
Amap to 0, while names beginning withZmap to 25. - 70
Why should a hash function's result be nonnegative?
Model answer
The result is used as an array index, and negative indices do not identify valid buckets.
Explanation
Using an unsigned integer can express the intended nonnegative range more clearly.
- 71
What is a collision in a hash table?
Model answer
A collision occurs when two or more keys map to the same bucket.
Explanation
A finite number of buckets cannot uniquely represent every possible input, so collisions are unavoidable in general.
- 72
How can linked lists resolve collisions in a hash table?
Model answer
Each array bucket can point to a linked list containing all keys that hash to that bucket.
Explanation
This approach is called chaining and allows multiple values to share one bucket.
- 73
What is a hash table?
Model answer
A hash table combines an array of buckets with a mechanism, often linked lists, for storing key-value pairs according to their hash values.
Explanation
It is a common implementation of the dictionary abstract data type.
- 74
Why can a hash table be faster than one linked list for searching?
Model answer
The hash function directs the search to a particular bucket instead of requiring the entire collection to be scanned.
Explanation
With a good distribution of keys, each bucket's linked list is much shorter than one list containing all keys.
- 75
Why does a hash table with chained collisions still have O(n) worst-case search time?
Model answer
If many keys collide in one bucket, searching that bucket's linked list may require examining all n keys.
Explanation
A hash table is efficient only when its hash function distributes keys reasonably evenly.
- 76
What is the trade-off when a hash function uses more characters of a key?
Model answer
Using more characters can reduce collisions but requires more buckets and therefore more memory.
Explanation
A table indexed by three-letter combinations has many more possible positions than one indexed only by the first letter.
- 77
What is a trie?
Model answer
A trie is a tree made of arrays in which paths represent sequences of characters in keys.
Explanation
Each node contains character-indexed child pointers that lead to the next character.
- 78
How is a word represented in a trie?
Model answer
The word is represented by a path of non-null pointers corresponding to its successive characters, plus an indicator showing where the word ends.
Explanation
The word itself need not be stored as one contiguous string in the trie.
- 79
How can a trie store words where one is a prefix of another?
Model answer
A word-ending marker can identify the end of the shorter word while the path continues to represent the longer word.
Explanation
For example, one path can represent both a shorter word and an extended word sharing its characters.
- 80
What is the lookup time for a trie in terms of the key length?
Model answer
Lookup takes time proportional to the key's length, which is effectively constant when key lengths have a fixed practical maximum.
Explanation
The number of stored keys does not determine how many character links must be followed.
- 81
Why can a trie use more memory than a hash table?
Model answer
Each trie node may contain an array of pointers for every possible character, most of which may be
NULLand unused.Explanation
The potential constant-time lookup comes at the cost of substantial memory overhead.
- 82
How can a hash table or trie store key-value pairs rather than only keys?
Model answer
The structure can associate each stored key or terminal node with its corresponding value, such as a phone number.
Explanation
This allows these structures to implement dictionaries such as contact lists or word-definition mappings.
- 83
What general resource trade-off appears repeatedly among arrays, linked lists, trees, hash tables, and tries?
Model answer
Improving speed or flexibility often requires additional memory, while saving memory may increase running time or limit growth.
Explanation
Choosing a data structure requires balancing time, space, and implementation complexity for the intended application.

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