- Learn
- Computer Science & IT
- Programming
- Data Structures and Algorithms
- Linear Data Structures
Linear Data Structures: Arrays, Lists, Stacks and Queues
IntermediateLesson 3 of 10 in Data Structures and Algorithms Course
What you will learn
- Separate what a structure promises (its operations and how they behave) from how it stores data, and use a simple model of memory to predict what each way of storing data costs.
- Specify an abstract data type and keep it apart from its implementationDefine an abstract data type by its operations, their effects and their error cases, and see how one abstract data type can have several implementations with different costs.
- Predict costs from how memory stores dataUse a simple model of memory to see why array indexing is fast, why an array cannot simply grow in place, and what references and locality mean for linked structures.
- Specify an abstract data type and keep it apart from its implementation
- Work with fixed-size arrays, implement a dynamic array that resizes itself, and explain why appending stays fast over any long run even though an occasional append copies every element.
- Use static arrays and count the cost of shiftingRead, update, insert and delete in a fixed-capacity array, and count how many elements each operation has to move.
- Implement a dynamic arrayKeep size and capacity apart, and write the append, insert and delete methods of an array that replaces its storage when it fills up.
- Explain the cost of resizing with amortized analysisCount the copying work in a long run of appends, explain why doubling gives a constant amortized cost and growing by a fixed amount does not, and avoid resizing back and forth.
- Use static arrays and count the cost of shifting
- Implement singly, doubly and circular linked lists, change their links in a safe order, and know which of their operations are fast and which are not.
- Implement a singly linked listBuild a list of nodes joined by next references, and insert, remove and traverse at the head, at the tail and after a given node.
- Implement doubly and circular linked listsAdd backward links and sentinel nodes so that inserting and removing anywhere takes constant time, and link the last node back to the first for round-robin work.
- Implement a singly linked list
- Implement the three restricted-access abstract data types with arrays and linked lists, and apply them to classic problems such as matching brackets, evaluating expressions and serving requests in order.
- Use and implement a stackApply last-in, first-out access, implement a stack with a Python list or a linked list, and use it to match brackets, evaluate postfix expressions and track history.
- Use and implement a queueApply first-in, first-out access, implement a queue with a circular array or a linked list, and avoid the slow list-based queue.
- Use and implement a dequeAdd and remove at both ends of a double-ended queue, implement it with a circular array or a doubly linked list, and use Python's deque for buffers, rotation and sliding windows.
- Use and implement a stack
- Compare the costs of every structure in this material side by side, and choose the one that fits how a program reads and changes its data, with a justification based on those costs.
- Compare operation costs across structuresSet the costs of arrays, linked lists, stacks, queues and deques side by side, and weigh worst-case against amortized bounds, memory use and real-world speed.
- Match an access pattern to a structureFollow a short method to choose a structure from the operations a program performs, and justify the choice with the costs of those operations.
- Compare operation costs across structures
Linear Data Structures study guide
1Describe data structures through abstract data types and memory
An interface describes what operations mean; a memory layout explains what they cost. Connect those two views by specifying a collection, tracing the references that store it, and identifying the conditions its methods must preserve. The same ordered data can live in contiguous slots or a chain of nodes, and that choice changes how the program reaches and changes an element. Python examples make both the interface and the stored state visible.
1.1 Interfaces, implementations, and invariants
A collection can promise a behavior without committing to a memory layout. That promise lets you reason about a program before choosing how to store its data.
Specify the behavior
An abstract data type (ADT) describes operations and their meaning. For each operation, specify its inputs, return value, effect on the collection, and error cases. For a stack, push(e) adds an element at the top; pop() removes and returns the top; top() reads it without removal. is_empty() and len() report the state. An empty pop() or top() raises an exception.
This contract makes client code predictable. If None is a valid stored value, returning None for an empty pop would make success and failure indistinguishable. An exception reports failure separately.
The sequence ADT arranges items by position. It supports indexed reads and updates, insertion, deletion, and ordered traversal. A set interface instead finds, inserts, and deletes by key. Position 4 means a place in a sequence; key 4 means the identity used to find an item.
Choose the representation
A data structure supplies the storage and algorithms behind an ADT. Both dynamic arrays and linked lists can implement a sequence, with different costs:
| Sequence operation | Dynamic array | Linked list |
|---|---|---|
| Read an arbitrary index | ||
| Insert at the front |
The interface alone does not tell you these costs. A class is a programming tool for implementing a contract, not the ADT itself. The same ADT can be implemented in different languages and with different structures.
Hide internal details
Here is a complete small stack wrapper. The list's end is the top.
class Empty(Exception):
pass
class ArrayStack:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self) == 0
def push(self, e):
self._data.append(e)
def top(self):
if self.is_empty():
raise Empty("stack is empty")
return self._data[-1]
def pop(self):
if self.is_empty():
raise Empty("stack is empty")
return self._data.pop()
After pushing "draft" and then "save", top() returns "save" and leaves the size at 2. pop() returns "save" and leaves the size at 1. The wrapper exposes no operation for changing a middle element. Client code that uses this interface can also use a linked implementation with the same behavior.
In Python, an initial underscore marks an internal attribute by convention; it does not prevent access. Reaching into _data breaks the separation that makes replacement possible.
State what must stay true
A representation invariant describes a valid internal state. Examples include "The size counter equals the number of stored elements" and "The tail refers to the final node, or is None when empty." A method can temporarily change links while it runs, but must restore the invariant before returning. Check both the returned result and the stored state when debugging: a method can return the right element while leaving a stale tail behind.
Key Takeaways
- An ADT specifies behavior, including errors; a data structure implements it.
- One ADT can have several implementations with different operation costs.
- Client code stays independent when it uses only the public interface.
- Every method must restore the representation invariant before returning.
1.2 Addresses, references, and locality
Array access and linked-list access do different work because they find elements differently. A simple memory model makes those costs visible.
Locate an array element
Treat memory as a row of numbered bytes. An address identifies a byte; reading or writing a fixed-size word at a known address takes constant time in this model. Computing an address and following a reference also take time. Memory examples here use 8-byte words.
An array reserves one contiguous block with equal-size slots. Its index gives an offset from the start:
For 8-byte numbers starting at address 2000, index 7 is at . The calculation has the same number of steps for index 7 as for index 7000, so access is . Index 0 needs no offset. With length n, the last valid nonnegative index is n - 1; index n is out of bounds. Python reports an invalid list index with IndexError.
A row-major two-dimensional array lays out complete rows in sequence. With C columns, skip r * C slots to reach row r, then c more to reach its column:
In a 4 by 5 table of 8-byte values starting at 1000, position (2, 3) is 13 slots from the start, at . This formula describes a flat rectangular layout; a Python list of row lists instead stores references to separate row objects.
Store values or references
A compact array stores values directly, all of one type. For example, array('i', [3, 1, 4]) from Python's array module stores C integers; bytes stores byte values. A referential array, such as a CPython list, stores equal-size references to objects. The objects can have different types and sizes because the slots hold their references, not the objects themselves.
Copying a reference does not copy its object:
grid = [[0] * 3] * 3
grid[0][0] = 1
# [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
Multiplication repeats references to one inner list. All three rows therefore show the mutation. To build independent rows, create each row separately:
grid = [[0] * 3 for _ in range(3)]
grid[0][0] = 1
# [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
Follow links and use nearby memory
A linked-list node stores an element and a reference to the next node. Nodes can occupy unrelated addresses. Starting at the head, reaching index i requires following i links: time. Each link is cheap, but the number of links grows with the position.
Arrays also benefit from locality. A processor loads nearby memory into its cache in chunks, so scanning consecutive slots often reuses data already loaded. Scattered nodes can cause more waiting for memory. Both full traversals cost , yet the array often runs faster. Linked nodes also need link fields and separate-object overhead.
An array's neighboring memory may belong to other data, so growth generally requires a new block and a copy. Spare slots postpone that copy; they do not change the address formula within the current block.
Key Takeaways
- Contiguous equal-size slots make address calculation and indexing constant time.
- Row-major indexing uses the column count to skip complete rows.
- A Python list stores references; repeated references can share one mutable object.
- Linked indexing follows a chain, while array traversal often benefits from locality.
- Growing an array may require allocating a new block and copying its elements.
2Build and analyze arrays that grow
An array makes indexed access cheap, but inserting into its sequence can move many elements. Growth adds another kind of work: replacing full storage and copying its contents. Build those operations with explicit size and capacity, then count a complete run of appends to explain their amortized cost. Safe shift directions and separate resize thresholds connect the implementation details to its correctness and performance.
2.1 Packed arrays and safe shifting
A fixed-capacity array can hold a sequence shorter than its storage. To preserve position-based access, keep the sequence packed at the front and track how many slots are in use.
Separate storage from the sequence
For data = [None] * 8, capacity is 8. If the sequence contains "A", "C", and "D", its size is 3 and the used indices are 0, 1, and 2. Reading or updating a valid position costs . A full static array cannot accept another element without replacement storage.
A read or deletion requires 0 <= k < n. Insertion allows 0 <= k <= n: inserting at n means adding just after the last element. The unused slots are storage, not extra elements in the sequence.
Insert by shifting right
To insert "B" at index 1 in the three-element sequence, move "D" from 2 to 3, then "C" from 1 to 2. Finally write "B" at 1 and increase the size to 4. The result is ['A', 'B', 'C', 'D'] followed by unused slots.
The loop must start at the back. Starting with data[2] = data[1] would overwrite "D" before it was saved. In general, shift the used positions from n - 1 down through k:
# Requires a valid insertion index and a spare slot.
for j in range(n, k, -1):
data[j] = data[j - 1]
data[k] = value
n += 1
Exactly old elements move, where n is the size before insertion. Inserting at index 3 of a 10-element sequence moves indices 3 through 9: 7 moves. Include the new write and size update when stating the time: . At the back this is ; at the front it is .
Delete by shifting left
Deleting index 1 from ['A', 'B', 'C', 'D'] saves "B", copies "C" into 1, and copies "D" into 2. The last formerly used slot must then be cleared:
# Requires 0 <= k < n.
removed = data[k]
for j in range(k, n - 1):
data[j] = data[j + 1]
data[n - 1] = None
n -= 1
Clearing the slot releases the array's reference to the former last element. It also keeps the unused region easy to inspect. Clearing is not what removes the element from the logical sequence; the size determines which slots belong to it.
Deletion moves elements and costs including constant bookkeeping. Deleting index 3 from size 10 moves 6 elements. Deleting the final element moves none but still takes constant time.
Distinguish lookup from search
Knowing an index gives immediate access. Knowing a value does not reveal its index. An unsorted array may require inspecting all n entries, so linear search is . A sorted array permits binary search in by repeatedly halving the remaining interval, but maintaining sorted order still requires shifts on insertion.
A static array fits a known maximum, such as a fixed-size image or a sensor buffer. Its fixed storage removes resize costs; the access pattern still determines whether shifting is expensive.
Key Takeaways
- Used elements occupy indices 0 through size minus 1 without gaps.
- Shift right from the back for insertion; shift left from the gap for deletion.
- Insertion moves n − k elements, while deletion moves n − k − 1.
- Constant-time indexing does not make value search constant time.
- A fixed capacity prevents resizing but does not prevent shifting.
2.2 A dynamic array implementation
A dynamic array replaces its backing storage when it fills up. Its public sequence grows while each individual backing array keeps a fixed capacity.
Keep size and capacity distinct
Size counts stored elements. Capacity counts available slots. With size 5 and capacity 8, positions 0 through 4 hold elements and positions 5 through 7 are unused. Reads and updates check against size, even though the backing array has more slots.
The implementation below starts at capacity 1 and doubles when full. It deliberately accepts only nonnegative indices, so the bounds stay explicit.
class DynamicArray:
def __init__(self):
self._n = 0
self._capacity = 1
self._A = [None]
def __len__(self):
return self._n
def _resize(self, capacity):
B = [None] * capacity
for k in range(self._n):
B[k] = self._A[k]
self._A = B
self._capacity = capacity
def get(self, i):
if not 0 <= i < self._n:
raise IndexError("invalid index")
return self._A[i]
def set(self, i, value):
if not 0 <= i < self._n:
raise IndexError("invalid index")
self._A[i] = value
def append(self, value):
self.insert(self._n, value)
def insert(self, k, value):
if not 0 <= k <= self._n:
raise IndexError("invalid index")
if self._n == self._capacity:
self._resize(2 * self._capacity)
for j in range(self._n, k, -1):
self._A[j] = self._A[j - 1]
self._A[k] = value
self._n += 1
def delete(self, k):
if not 0 <= k < self._n:
raise IndexError("invalid index")
value = self._A[k]
for j in range(k, self._n - 1):
self._A[j] = self._A[j + 1]
self._A[self._n - 1] = None
self._n -= 1
return value
_resize is internal: callers supply a positive capacity large enough for the stored elements. Copying finishes before _A is replaced, so every read during the loop still uses the old storage. The copied entries are references; the objects are not duplicated.
Trace the growth
Append 10, 20, 30, 40, and 50. The first append fills capacity 1. The second copies 1 element into capacity 2. The third copies 2 into capacity 4. The fourth fits without a copy. The fifth copies 4 into capacity 8. Final size is 5, with 3 spare slots and 7 copied entries across all resizes.
A read at index 5 must fail: that slot exists in storage but is beyond the sequence. Insertion at index 5 is valid because it extends the sequence at its end.
Account for each kind of work
An insert with room costs for shifting and the new write. If it resizes, it also copies all n existing entries, making that individual insertion even at the end.
The implementation keeps its capacity after deletions. To release spare memory, it can halve capacity at one-quarter occupancy while preserving a minimum capacity of 1. Shrinking at half occupancy would put it directly on the growth boundary and cause repeated copying under alternating appends and pops.
CPython's list, Java's ArrayList, and C++'s std::vector provide dynamic arrays. Python hides capacity and reports size with len. Rebuilding storage with one extra slot for every append loses the benefit of spare capacity and makes a long run of appends quadratic.
Key Takeaways
- Size counts elements; capacity counts reserved slots.
- Resize before writing into a full backing array, and copy before replacing it.
- Read and update bounds use size; insertion also allows the position at size.
- Shifting and resizing are separate sources of insertion cost.
- A single resizing append is linear even though appends are cheap over a run.
- Shrinking at one-quarter occupancy leaves space between resize thresholds.
2.3 Why proportional growth keeps appends cheap
A fast typical append and a slow resizing append belong to the same implementation. Amortized analysis gives a guarantee for the whole run without pretending that each operation costs the same.
Count the complete run
Start empty at capacity 1 and double whenever full. During 16 appends, resizes copy 1, 2, 4, and 8 entries: 15 copies. The 16 new entries also need writes, so there are 31 element operations. The next append copies 16 entries before writing its new value.
The 17th operation is expensive, but it does not make the complete run quadratic. For n appends, the copied array sizes form a geometric series:
Here is the largest power of 2 below n; for a run with no resize the copy total is zero. Adding n new writes gives fewer than element operations. Allocation and initialization of these geometrically growing arrays also have linear total cost in this model.
Thus appending is amortized . This bounds the worst-case total over every run of a given length and divides by the number of operations. It is not an average over likely inputs or a claim that resizes are rare by chance. A single append still has worst-case time.
Save work credits
Another way to see the bound is to charge 3 units for each append: 1 for the new write and 2 saved toward copying. While an array of capacity c goes from half full to full, its c/2 appends save c units. Those credits pay for copying c entries at the next doubling. Early saved credits cover the initial small resize. The charge stays constant even when the actual cost jumps.
Avoid fixed-step growth
Growing by a fixed number creates a very different sum. From capacity 4, adding 4 slots each time while appending 100 elements copies
Doubling from capacity 4 copies only . For 1000 elements the totals are 124500 and 1020. Fixed-step growth repeatedly copies an array only a little larger than before, giving total work and amortized work per append.
Any fixed growth factor greater than 1 gives amortized constant-time append. A factor of 1.5 saves unused space compared with doubling but copies more often. CPython grows a list proportionally too, with roughly one-eighth extra space plus a small constant, rather than following the textbook doubling sequence exactly.
Leave a gap before shrinking
Suppose size and capacity are both 8. Append once: copy 8 entries into capacity 16 and reach size 9. Pop once: return to size 8. If half-full storage immediately shrinks, copy 8 entries back into capacity 8. Alternating these operations now copies a linear number of entries each time.
Instead, halve only at one-quarter occupancy. Capacity 16 then shrinks at size 4 to capacity 8, leaving it half full. Many appends are needed before growth; many deletions are needed before another shrink. With a fixed minimum capacity, end appends and pops remain amortized .
Python list indexing and indexed assignment cost . End append and pop cost amortized ; indexed insertion and removal also pay for suffix shifts, reaching at the front. A program that needs a bound on every operation can reserve capacity or use fixed-size storage to avoid a whole-array resize pause.
Key Takeaways
- Amortized cost bounds a complete run, not a distribution of random inputs.
- Doubling from capacity 1 makes fewer than 2n copies during n appends.
- One append can be linear while appends are amortized constant time.
- Fixed-step growth makes a long run of appends quadratic.
- A fixed proportional growth factor trades copying frequency for spare memory.
- Separate grow and shrink thresholds prevent repeated resize thrashing.
- Strict per-operation timing needs more than an amortized guarantee.
3Build linked lists and update their links safely
Linked lists grow by connecting nodes, so edits depend on which references are already available. Build a singly linked chain, handle its empty and one-element states, then add backward links and sentinels for local edits at either end. A circular chain supports repeated turns with a change of starting point. Tracing every changed reference shows why some operations stay constant time while others need a walk.
3.1 A singly linked list implementation
A singly linked list stores its sequence in nodes connected by next references. Keeping both head and tail makes adding at either end cheap, but it does not make removing at either end equally cheap.
Build a chain
Each node holds an element and its successor. The final node points to None. An empty list has no first or last node, so both head and tail are None and size is zero.
class _Node:
__slots__ = ("element", "next")
def __init__(self, element, next_node=None):
self.element = element
self.next = next_node
class SinglyList:
def __init__(self):
self.head = self.tail = None
self.size = 0
def add_first(self, value):
node = _Node(value, self.head)
self.head = node
if self.size == 0:
self.tail = node
self.size += 1
def add_last(self, value):
node = _Node(value)
if self.size == 0:
self.head = node
else:
self.tail.next = node
self.tail = node
self.size += 1
def delete_first(self):
if self.size == 0:
raise IndexError("list is empty")
value = self.head.element
self.head = self.head.next
self.size -= 1
if self.size == 0:
self.tail = None
return value
def __iter__(self):
walk = self.head
while walk is not None:
yield walk.element
walk = walk.next
__slots__ is optional; it reduces per-node attribute storage. It does not change the links or the algorithms.
Preserve the old chain before replacing a link
For 8 → 3 → 5, adding 1 first creates a node pointing to the old head, then makes that node the new head. The chain becomes 1 → 8 → 3 → 5. Assigning the new head before saving the old one would lose the only entry point to the old chain.
Insertion after a held node follows the same order:
new = _Node(value, node.next)
node.next = new
if self.tail is node:
self.tail = new
self.size += 1
The new node first remembers the successor. Only then does the predecessor point to the new node. Updating the tail when inserting after the old tail keeps later tail insertions correct.
Deleting the head also has an empty-state case. When its successor is None, the removed node was the only element. Leaving tail unchanged would keep a reference to a node no longer in the sequence, and a later append could attach to that detached node.
Include the cost of finding a position
Adding or deleting at the head costs . Adding at the tail costs with the tail reference. Removing the tail still needs its predecessor: walk from the head to find the node whose next is the old tail. That takes in the worst case.
Likewise, inserting after a node already held costs , but insertion at index i first locates the predecessor and costs . An array with spare capacity instead shifts the suffix in . The linked list favors the front; the array favors the back.
Traversal and unsorted value search cost . A singly linked list is therefore a good stack at its head, or a queue that adds at the tail and removes at the head. Both access patterns avoid predecessor searches.
Key Takeaways
- An empty head-and-tail list keeps both references at None.
- Save the successor before replacing a link.
- Head insertion and removal are constant time; tail insertion needs a tail reference.
- Tail removal still needs a linear predecessor search.
- Include position lookup when analyzing indexed edits.
- A stack uses the head; a queue adds at the tail and removes at the head.
3.2 Backward links, sentinels, and circles
A second link changes what you can do with a node already in hand. Closing a chain into a circle changes how you move through repeated turns.
Edit a doubly linked list
A doubly linked node stores both prev and next. Given a real node, you can reach either neighbor directly. This permits constant-time deletion without searching for a predecessor.
Two sentinel nodes simplify the ends. A header sits before the first element and a trailer after the last. Neither counts as an element. Initially header.next is trailer, trailer.prev is header, and size is zero. Every real node has a neighbor on both sides, even when it is the only element.
These helpers operate on a list with those sentinels. The insertion helper receives adjacent nodes p and q; deletion receives a real node, never a sentinel.
class _DNode:
def __init__(self, element, prev=None, next_node=None):
self.element = element
self.prev = prev
self.next = next_node
# Methods inside the list class:
def _insert_between(self, value, p, q):
node = _DNode(value, p, q)
p.next = node
q.prev = node
self.size += 1
return node
def _delete_node(self, node):
value = node.element
p, q = node.prev, node.next
p.next = q
q.prev = p
self.size -= 1
node.prev = node.next = None
node.element = None
return value
To insert at the front, use the header and its successor. At the back, use the trailer's predecessor and the trailer. The same insertion code handles an empty list because its sentinels are already adjacent.
For A ↔ B ↔ D, insert C by first giving C links to B and D, then setting B.next = C and D.prev = C. To delete A, connect header.next to B and B.prev to the header. Updating only one direction produces a list that may look correct forward but fail backward.
A held position makes local insertion, deletion, and one-step cursor movement . Index access remains , though a size-aware list can start from the nearer end. In size 10, index 8 is one backward link from the final element. Extra backward links cost storage and more updates per edit.
Close the final link
A circularly linked list makes the last node point to the first. In a nonempty list, storing only tail is enough to recover the head as tail.next. Rotating the first element to the back needs only:
tail = tail.next
No node moves and no link changes. The head is now the node after the new tail. For A → B → C → A with tail C, the new tail is A and the logical order becomes B, C, A.
A circular traversal stops after size nodes or upon returning to the start. Waiting for None would loop forever. An empty circular list needs a separate empty state, usually tail = None; the formula tail.next applies when nonempty.
Give tasks repeated turns
In round-robin scheduling, run the front task for one time slice. Remove it if complete; otherwise rotate it to the back. For A, B, and C needing 3, 1, and 2 slices, the execution order is A, B, C, A, C, A. B leaves after its first turn, so later rounds skip it. A circular list models the recurring order without moving every element in storage.
Key Takeaways
- Backward links allow constant-time deletion of a held real node.
- Sentinels give every real node two neighbors, including at the ends.
- Insertion and deletion must repair both directions.
- A held position is different from an index that must first be located.
- In a nonempty circular list, tail.next is the head.
- Rotation can change only the tail reference.
- Circular traversal must stop by count or return to its starting node.
4Use stacks, queues and deques to solve problems
Stacks, queues, and deques restrict access in ways that match recurring programming tasks. Choose the right end for each operation, trace the stored state, and apply the ordering to nested brackets, partial expression results, arrival order, and recent history. Circular indexing makes a queue work without shifts, while two-ended access supports buffers and rotation. The implementation determines the cost behind each shared interface.
4.1 Stacks for nested work and history
A stack exposes the most recently added unfinished item. This last-in, first-out order matches nested tasks: an inner task finishes before the outer task resumes.
Put the top at an efficient end
With a Python list, use the end as the top: append pushes, pop() removes, and stack[-1] peeks. Push and pop cost amortized ; peek costs . Using insert(0, value) and pop(0) would shift the remaining elements on every change.
With a singly linked list, use the head as the top. Both push and pop are worst-case in the memory model, with no backing-array resize. Putting the top at its tail would make pop search for the predecessor.
An empty pop or peek is an error. An explicit exception keeps failure distinct from a legitimate stored None.
Match brackets with the last unmatched opener
Scan text from left to right. Push each opening bracket. At a closing bracket, require a nonempty stack whose top is the matching opener. After the scan, require an empty stack.
def balanced(text):
openers = "([{"
matching = {")": "(", "]": "[", "}": "{"}
stack = []
for char in text:
if char in openers:
stack.append(char)
elif char in matching:
if not stack or stack.pop() != matching[char]:
return False
return not stack
For "{[()()]}", each closer removes its matching top, leaving nothing at the end. In "([)]", ) meets [ on top, so matching fails immediately. In "(()", a remaining opener causes failure after the scan. In "())", the last closer finds an empty stack. Equal counts alone miss the nesting error in "([)]". Non-bracket characters, as in "a[b(c)d]e", are skipped.
Evaluate postfix expressions
A postfix operator comes after its operands. Push numbers. For an operator, pop the right operand first and the left operand second, compute, then push the result.
For 5 1 2 + 4 * + 3 -, begin with [5, 1, 2]. The + replaces 1 and 2 with 3, giving [5, 3]. Push 4; * replaces 3 and 4 with 12, giving [5, 12]. The next + gives [17]. Push 3 and subtract to obtain [14].
Operand order matters: the final step computes 17 - 3, not 3 - 17. For a valid binary postfix expression, every operator has two operands and exactly one result remains at the end. The stack holds partial results still needed by later operators.
Maintain two directions of history
A browser can use a back stack, a current page, and a forward stack. Visiting a new page pushes the current page onto back and clears forward. Back pushes the current page onto forward, then pops back to choose the page to display. Forward reverses those roles.
After visiting A, B, and C, Back displays B with A in back and C in forward. Opening D now puts B on back and clears C from forward. The new visit creates a new continuation of the history.
Undo actions, sequence reversal, backtracking, and the call stack use the same ordering. A call frame stays active until its function returns; a deeper call finishes before its caller continues. Very deep recursion can exhaust the call stack.
Key Takeaways
- LIFO exposes the most recently pushed item.
- Use a list end or a singly linked head as the top.
- Bracket matching checks type, nesting order, and the final empty state.
- In postfix evaluation, pop the right operand before the left.
- A new browser visit clears the forward stack.
- Empty pop and peek must report an error.
4.2 Queues without front shifts
A queue serves the oldest waiting element first. Adding at the back and removing at the front preserves arrival order, but the storage must support those ends efficiently.
Move the front index
A circular array queue stores capacity N, the first element's index front, and the number of elements size. Logical position k lives at (front + k) % N. The remainder wraps a physical index back to zero.
On enqueue, write at (front + size) % N and increment size. On dequeue, save and clear data[front], advance front modulo capacity, and decrement size. The other elements stay where they are.
These methods fit a class initialized with data = [None] * N, front = 0, and size = 0, where N is positive:
def enqueue(self, value):
if self.size == len(self.data):
self._resize(2 * len(self.data))
slot = (self.front + self.size) % len(self.data)
self.data[slot] = value
self.size += 1
def dequeue(self):
if self.size == 0:
raise IndexError("queue is empty")
value = self.data[self.front]
self.data[self.front] = None
self.front = (self.front + 1) % len(self.data)
self.size -= 1
return value
def _resize(self, capacity):
old = self.data
new = [None] * capacity
for k in range(self.size):
new[k] = old[(self.front + k) % len(old)]
self.data = new
self.front = 0
first() reads the front without changing it, after the same empty check. len() reports size and is_empty() tests size zero.
Trace wraparound and growth
With capacity 5, enqueue A, B, C, and D. Dequeue twice, returning A and B. Now front = 2, size = 2, and C and D remain in slots 2 and 3. Enqueue E at slot 4, F at slot 0, and G at slot 1. Physical storage is [F, G, C, D, E], but logical order is C, D, E, F, G.
Enqueueing H triggers growth to capacity 10. Copy in logical order into indices 0 through 4, reset front to 0, then write H at 5. Copying physical slots in order would incorrectly serve F and G before C.
Track size explicitly: the next write position equals front in both an empty and a full ring. An alternative design reserves one unused slot, but then usable capacity is one less than the array length.
Choose a linked or library queue
A singly linked queue enqueues at its tail and dequeues at its head. Both operations are worst-case in the model; removing the last item must clear both endpoint references. Reversing the ends makes dequeue search for the tail's predecessor.
For ordinary Python code, collections.deque supplies append and popleft with end costs. A list's pop(0) moves the remaining references. Emptying n elements that way moves references, giving total work. A circular array with doubling gives amortized enqueue and dequeue when it does not shrink.
Queues fit print jobs, message buffers, and breadth-first exploration. queue.Queue adds locking and blocking operations for work passed between threads. A priority queue uses priority to choose what leaves; arrival order alone does not determine its next element.
Key Takeaways
- FIFO removes elements in arrival order.
- Circular storage moves the front index instead of shifting the sequence.
- Enqueue uses (front + size) % capacity.
- Resize copies logical queue order and resets front.
- Size distinguishes a full ring from an empty ring.
- A linked queue adds at the tail and removes at the head.
- Repeated list.pop(0) makes draining a queue quadratic.
4.3 Deques for work at both ends
A deque, pronounced "deck," is a double-ended queue. It can add, inspect, and remove at either end, so it supports access patterns that need more freedom than a stack or queue.
Extend the end operations
The ADT offers add_first, add_last, delete_first, and delete_last, with first, last, is_empty, and len. Using one end for both insertion and removal gives a stack. Inserting at one end and removing at the other gives a queue. The noun deque names the collection; dequeue names the act of removing from a queue.
In a circular array of positive capacity N, a front insertion first computes front = (front - 1) % N, then writes the new element there and increments size. A back insertion writes at (front + size) % N. A back deletion uses (front + size - 1) % N before decreasing size. Front deletion clears the old front and advances it.
In Python, (0 - 1) % 5 is 4, which wraps backward correctly. In Java and C, the negative remainder requires (front - 1 + N) % N for this one-step move. Resizing must still copy elements in logical order. With proportional growth and safe shrink thresholds, end operations are amortized .
A sentinel-based doubly linked list also supports every deque end operation in worst-case . A singly linked list cannot give that bound for deleting the last element, because it lacks a backward link to the new tail.
Use Python's deque
from collections import deque
d = deque(["A", "B"])
d.append("C") # A, B, C
d.appendleft("Z") # Z, A, B, C
right = d.pop() # returns C
left = d.popleft() # returns Z
extend appends multiple values; extendleft repeatedly appends values at the left. For d = deque([3]), d.extendleft([1, 2]) gives [2, 1, 3] because 2 is added at the left after 1. Empty pop and popleft raise IndexError.
CPython implements a deque with doubly linked fixed-size blocks of 64 slots. End appends and pops touch an end block and sometimes add or remove a block; they never copy the whole collection. Indexing near the ends is constant time, but indexing the middle is . A deque is therefore a poor replacement for a list when arbitrary indexed reads dominate.
Retain recent items and rotate turns
A bounded deque automatically discards from the opposite end when an append would exceed its limit:
d = deque(maxlen=3)
for value in [1, 2, 3, 4, 5]:
d.append(value)
# d holds 3, 4, 5
This fits a recent-event history or a sliding window: new readings enter at the back and old readings expire at the front. A bounded undo history can pop recent actions while dropping the oldest when full.
Positive rotation moves right. Rotating [1, 2, 3, 4, 5] by 2 gives [4, 5, 1, 2, 3]; rotating the original by -1 gives [2, 3, 4, 5, 1]. One left rotation sends the front item to the back for round-robin turns.
To check a palindrome, load its characters into a deque and compare popleft() with pop() until at most one remains. For "level," compare l with l, then e with e; the middle v needs no partner. "robot" fails when r and t differ. Each character is removed at most once, so the whole check is .
Java's ArrayDeque implements a deque with circular-array storage; LinkedList provides deque operations with a doubly linked list.
Key Takeaways
- A deque supports insertion and removal at both ends.
- Circular arrays and doubly linked lists support efficient deque operations.
- Python deque appends and pops do not copy the whole collection.
- Middle indexing in a deque is linear.
- Bounded deque appends discard from the opposite end.
- Positive rotation moves items right; negative rotation moves them left.
5Choose and justify the right linear structure
A useful structure makes the program's frequent work cheap while meeting its storage and timing needs. Compare operations by position, include the cost of locating a node, and distinguish a worst-case bound from an amortized one. Then turn concrete requirements into an ordering contract and an implementation choice. Memory overhead and locality explain why equal asymptotic bounds can still lead to different measured speeds.
5.1 Compare costs with the access position included
An operation name is not enough to predict cost. State where the operation acts, how the position is supplied, and whether the bound applies to one operation or a whole run.
Compare sequence implementations
The table uses n for size. A singly linked list keeps both head and tail; a doubly linked list keeps endpoints or sentinels. Dynamic-array end changes have amortized bounds.
| Operation | Dynamic array | Singly linked list | Doubly linked list |
|---|---|---|---|
| Read arbitrary index | |||
| Add at front | |||
| Remove at front | |||
| Add at back | Amortized | ||
| Remove at back | Amortized | ||
| Search unsorted values |
Middle edits need a second question: do you already hold the position? A dynamic array shifts a suffix, reaching . A doubly linked list edits next to or deletes a held node in . A singly linked list needs the predecessor for deletion or insertion before a node. If an index or value must first be located, that search can make the complete linked edit .
A sorted array supports binary search in , but insertion into sorted order still moves entries. Direct indexing, value lookup, and maintaining sorted order are separate tasks.
Read the guarantee correctly
Worst-case bounds each operation in the model. Amortized bounds total work across a run, allowing individual linear resizes. A linked stack uses its head; a linked queue uses tail insertion and head deletion; a doubly linked deque uses both ends. These give worst-case constant-time link work.
A list-backed stack or resizing circular queue gives amortized constant-time end changes. CPython's block-linked deque gives constant-time end appends and pops without whole-collection copying. For a strict timing requirement, avoiding algorithmic resizing is useful, though actual elapsed time also depends on allocation and the runtime.
Include storage and real speed
A dynamic array reserves spare slots. Right after doubling, roughly half its capacity is unused, but its slots need no per-element link fields. A singly linked node adds one reference and a doubly linked node adds two, plus each node's separate-object overhead. In a referential array, the elements themselves also live outside the slot block; compare like-for-like stored objects when measuring memory.
Contiguous slots improve locality and reduce allocation frequency. Scattered nodes may require more cache misses and one allocation per element. Equal big-O bounds can therefore have different measured times. A sequential scan of a dynamic array is often faster than traversing a linked list, though both are linear.
Use timeit when those differences matter. Measure the operations the program actually performs at relevant collection sizes. Constructing data inside one timed case but outside another would compare setup work as well as the intended operation.
Key Takeaways
- Index access, endpoint changes, and value search are different operations.
- Linked middle edits are constant time only after the needed position is available.
- A singly linked tail reference does not make tail deletion constant time.
- Amortized bounds allow an occasional linear resize.
- Arrays trade spare slots for locality; nodes trade link storage for local edits.
- Measure representative workloads when constant factors matter.
5.2 Choose from the operations a program performs
Choose a structure by describing the program's work in terms of operations. A familiar class name becomes useful evidence only after you connect it to the access pattern.
Turn requirements into an access pattern
- List the reads, additions, removals, and searches, with their approximate frequency.
- Identify the position each uses: arbitrary index, front, back, or a node already held.
- Decide whether occasional resize pauses are acceptable and how large the collection may become.
- Choose the ADT that matches the ordering, then an implementation with suitable costs.
- Justify the frequent operations with explicit bounds.
For example, "remove the oldest request" means FIFO access. "Read measurement number 400" means indexed access. "Remove the item under the cursor" describes a held position only if the cursor actually retains a node reference.
Match common workloads
| Program behavior | Suitable structure | Reason |
|---|---|---|
| Undo newest action | List-backed stack | End push and pop are amortized |
| Serve arrivals oldest first | collections.deque as a queue | Append and popleft are |
| Append readings and read by day number | Dynamic array | Indexed reads are ; append is amortized |
| Move a cursor one place and edit there | Doubly linked list | Local movement and held-node edits are |
| Keep a fixed window without resizing | Fixed circular buffer | Endpoint updates take within reserved storage |
A bounded undo history adds an operation absent from an unlimited stack: discard the oldest action when the limit is reached. deque(maxlen=100) can drop from the old end while appending at the recent end. The same structure can still pop the most recent action.
Compare the whole workload
Suppose an application stores n readings, then performs m arbitrary indexed lookups. A dynamic array takes total time for the appends and reads. A linked list may take because each lookup can traverse a linear number of nodes. Cheap linked insertion does not compensate for a much more frequent slow read.
A playlist with a retained node cursor has a different pattern: next, previous, insert beside the cursor, and delete the current song. A doubly linked list gives constant-time local work. If the interface instead repeatedly asks for a song by number, those indexed searches must be counted too.
Match the timing and retention rules
For a monitor holding the last 60 readings, a bounded deque handles automatic expiration. A fixed circular buffer of capacity 60 makes the storage limit explicit and avoids resizing. When full, its insertion behavior must implement the retention rule, replacing the oldest entry and advancing front.
For recurring turns, a circular list rotates by changing its tail reference, while a deque supports end-to-end rotation. Select this behavior when participants return for more turns; a completed task must leave the cycle.
Write a defensible reason
"Requests arrive continuously and the oldest is served first. A deque gives constant-time append and popleft; using list.pop(0) would shift the waiting requests after every service." This names the ordering, the implementation, and the cost that matters.
A lookup by customer ID is a search by key, not by position. Unsorted linear structures need search. A sorted array permits lookup but pays to maintain order on changes. Frequent key lookups with frequent updates usually call for a hash table or search tree.
Key Takeaways
- List the frequent operations and how each position is obtained before choosing.
- Choose the ordering contract first, then its implementation.
- Include lookup work when comparing total workload costs.
- Bounded history needs efficient access to both recent and oldest items.
- Fixed buffers avoid resizing and need a clear full-buffer policy.
Linear Data Structures examples
1Connect an interface to its memory layout
11 steps
- 1IntroductionFollow one collection through two views
Suppose a program needs a collection whose newest item is removed first. Begin by describing that behavior, then ask how the items can live in memory.
Those are separate decisions. A public operation tells the program what to expect (the ADT contract); array slots or linked nodes determine the steps taken underneath. You will use a small stack to connect behavior, hidden state (kept valid by a representation invariant), and operation cost.
- 2ExplanationDescribe what pop promises
For a stack,
push(e)adds at the top andpop()removes and returns the most recent remaining item.top()reads that same item without removing it.A complete specification also covers failure: pop and top on an empty stack raise an exception. The contract says what the caller receives and how the state changes, without requiring an array or a node anywhere in that description.
- 3ExampleTrace a public interface
Push
"note", then"send". The stack's logical order is note below send. Callingtop()returns"send"and leaves two elements. Callingpop()returns"send"and leaves one.A list-backed implementation can use
appendand endpopinternally. A linked implementation can use head insertion and removal. The same trace works through either public interface, even though their stored states differ. - 4Key InsightKeep the state valid
A representation invariant describes a valid internal state. For a head-and-tail linked stack, empty means both endpoints are
None, and size must equal the number of reachable elements.A method can return the right value and still break this rule. Removing the only node but leaving tail on that removed node creates a failure for later operations. Inspect the new state as well as the returned result.
- 5ChallengeSeparate a contract from storage
A stack class replaces its Python list with singly linked nodes. The operation names, results, and error behavior stay the same. Has the ADT changed? What may change for an individual push?
---reveal---
The ADT is unchanged because its promised behavior is preserved. The data structure has changed. A list-backed push may occasionally resize, while linked head insertion uses a fixed number of link updates in the memory model.
- 6ExplanationCalculate an address directly
An array reserves equal-size slots in one contiguous block. Slot
istarts at the base address plusislot widths:For 8-byte slots starting at 2000, index 7 is at 2056. Any valid index needs one multiplication and one addition, so array indexing is constant time in the model. Reaching a later index does not require visiting earlier slots.
- 7ExampleSkip whole rows, then columns
A row-major table stores one complete row after another. With 5 columns, reaching row 2 skips 10 slots. Reaching column 3 then skips 3 more, for a flat offset of 13 slots.
For 8-byte values starting at address 1000, the address is . The column count supplies the row width; the number of rows does not belong in that multiplier.
- 8ExampleTrace references instead of copying objects
The expression
[[0] * 3] * 3makes one inner list, then repeats references to it. Assigninggrid[0][0] = 1changes that one object, so all three row views show[1, 0, 0].Use
[[0] * 3 for _ in range(3)]for independent rows. Each loop iteration constructs a different inner list. The outer array still stores references, but those references now identify separate objects. - 9ChallengeFind a row-major position
A flat table has 4 columns of 8-byte values and starts at address 600. What is the address of zero-based position
(2, 1)?---reveal---
Skip two rows of four values and one more value: 9 slots. The byte offset is , so the address is 672. Using 2 as the row width would skip too few entries; every preceding row contains all 4 columns.
- 10ChallengeConnect storage to the same interface
Two sequence classes both offer
get(i). One stores contiguous slots; the other stores a next-linked chain. Why can the same operation have different costs, and why can their complete scans differ in real speed?---reveal---
The interface specifies the result, not the representation. Array get calculates an address; linked get follows links. Both full scans are linear, but contiguous slots often share cache loads, improving locality.
- 11RecapRead the promise and the representation
When you meet a collection, identify its public behavior and then inspect how the stored state supports it. A method's result, failure behavior, and invariant belong in that check.
For performance, locate the work: address arithmetic, reference traversal, or copying. Sharing a public interface does not make two implementations equally fast, and copying references does not make independent copies of mutable objects.
2Build an array that grows without wasteful copying
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeparate two reasons an array does work
- 2ExampleOpen a gap from the back
- 3ExplanationCount a deletion separately
- 4ChallengeCount the moving suffix
- 5ExplanationKeep two counters with different meanings
- 6ExampleAllocate, copy, replace, append
- 7ExampleContinue the same growth trace
- 8ChallengeCheck the public bounds after growth
- 9ExampleCount sixteen appends as one run
- 10Key InsightUse the sum, not the number of resizes
- 11AnalogySet aside credits for the next copy
- 12ChallengeCompare different growth policies
- 13ExampleMake a bad shrink rule thrash
- 14TipLeave room between resize thresholds
- 15ChallengeCombine shifts and resize guarantees
- 16RecapAttach the bound to the work being counted
3Trace linked edits without losing nodes
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep the references needed for the next step
- 2ExplanationDescribe the empty and nonempty states
- 3ExampleInsert before changing head
- 4ExampleAppend and then remove at the head
- 5ChallengeRepair an empty-state bug
- 6Key InsightA tail reference is not a backward link
- 7ExplanationGive real endpoints neighbors
- 8ExampleInsert C between B and D
- 9ExampleDelete through both neighbors
- 10ChallengeSpot a one-direction repair
- 11ExampleRotate a circular list without relinking
- 12TipStop a circular traversal deliberately
- 13ChallengeInclude location work in a local edit
- 14RecapMatch the links to the work
4Use access order to solve sequence problems
19 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChoose which item should be accessible
- 2ExplanationPlace a stack top where changes are cheap
- 3ExamplePush the open brackets
- 4ExampleClose each group in nesting order
- 5ChallengeFind the first nesting failure
- 6ExampleKeep partial postfix results on a stack
- 7ChallengePreserve operand direction
- 8ConnectionMove history between two stacks
- 9ExplanationServe the front without shifting
- 10ExampleLet the physical slots wrap
- 11ExampleGrow from the logical front
- 12ChallengeTranslate a wrapped queue
- 13TipUse the right linked endpoints
- 14ExplanationAdd the other two endpoint operations
- 15ExampleExpire the oldest automatically
- 16ExampleRotate and compare opposite ends
- 17ChallengeFollow bounded retention from both ends
- 18ChallengeChoose ordering and retention together
- 19RecapLet the next-needed item choose the end
5Justify a structure using the complete workload
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTurn a class preference into a cost argument
- 2ExplanationCompare the exact access requested
- 3ChallengeUnpack a vague insertion claim
- 4Key InsightChoose the guarantee the program needs
- 5ExampleCount an indexed archive workload
- 6ExampleGive a cursor its own position
- 7ExampleMake a fixed retention rule explicit
- 8ChallengeJustify FIFO storage
- 9ChallengeRecognize a requirement that changes the choice
- 10RecapState a reason that another developer can check
Linear Data Structures practice questions
Set 1: Interfaces, memory, and array operations10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
What does rows contain after this code?
rows = [[0] * 2] * 4
rows[2][1] = 9
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Growth policies and linked-list changes10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Trace stacks, queues, and two-ended buffers10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
18 6 2 - / produce?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
d = deque([10, 20, 30], maxlen=4). After d.appendleft(5), d.append(40), d.rotate(1), and d.popleft(), what remains?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
8 3 2 * - 5 +. A bug reverses the left and right operands for every operator. What result does the buggy evaluator produce?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Find invariant failures and hidden costs10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
tail = tail.next, what are the head and tail?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Choose structures for complete workloads10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Abstract data type
Access pattern
Address
Aliasing
Amortized cost
B
Binary search
Bounded deque
Bracket matching
C
Call stack
Capacity
Circular buffer
Circular linked list
Compact array
Constant factor
Contiguous storage
D
Data structure
Deque
Dequeue
Doubly linked list
Dynamic array
F
FIFO
Fixed-step growth
Front index
G
Geometric growth
Growth factor
H
Head
I
Interface
K
Key-based lookup
L
LIFO
Linear search
Locality
M
Memory overhead
N
Node
O
Operation cost
P
Packed sequence
Palindrome
Position
Postfix expression
9 4 - computes 9 minus 4 because the first popped operand is the right one.Predecessor
Q
Queue
R
Random access
Reference
Referential array
Representation invariant
Resize thrashing
Resizing
Rotation
Round-robin scheduling
Row-major order
S
Sentinel
Sequence
Shifting
Singly linked list
Size
Sliding window
Stack
Static array
T
Tail
Top
Traversal
W
Workload
Worst-case cost
Wraparound
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.