Linear Data Structures
Examples and Intuition: Arrays, Linked Lists, Stacks, Queues
Read aloud is unavailable in this browser.
The Four Pillars of Linear Data Structures
Now that we understand the theoretical foundation of linear data structures—sequential organization, one-to-one relationships, and the distinction between logical and physical order—it's time to meet the four structures that embody these principles most directly.
Arrays, linked lists, stacks, and queues are the foundational linear data structures. Every programmer encounters them, and every computer science curriculum teaches them. But more importantly, they appear everywhere in real software:
- Arrays power everything from image pixels to database rows
- Linked lists enable flexible memory allocation and efficient insertions
- Stacks manage function calls, undo operations, and expression parsing
- Queues orchestrate task scheduling, message passing, and buffering
This page provides the conceptual foundation for each—the mental model, the key characteristics, and the intuition for when to use each one. Detailed implementations will follow in dedicated chapters.
By the end of this page, you will have a clear mental model for each of the four fundamental linear data structures, understand their distinguishing characteristics, and develop intuition for selecting the right structure for different problem types.
Arrays: The Contiguous Collection
An array is the most fundamental data structure—a fixed-size, ordered collection of elements stored in contiguous memory locations. It is the direct manifestation of computer memory itself: a sequence of slots, each accessible by its position.
The mental model:
Imagine a row of numbered lockers in a hallway. Each locker has a number (its index), and you can walk directly to any locker by its number without checking the others. That's an array.
Key characteristics:
- Contiguous storage: All elements sit side-by-side in memory
- Fixed size (in static arrays): Size is determined at creation
- Homogeneous elements: All elements are the same type and size
- O(1) random access: Any element is accessible instantly by index
- O(n) insertion/deletion: Modifying the middle requires shifting elements
- •Random access by index
- •Sequential iteration
- •Fixed-size collections
- •Cache-efficient processing
- •Multi-dimensional data (matrices)
- •Dynamic sizing (without resizing)
- •Insertions/deletions in middle
- •Frequent structural changes
- •Unknown or highly variable size
- •Memory efficiency for sparse data
Real-world intuition:
Think of arrays when you think of:
- Images: A 2D array of pixels, each accessible by (row, column)
- Spreadsheets: Rows and columns of cells, accessed by position
- Audio samples: A sequence of amplitude values, processed in order
- Leaderboards: Fixed-length ranking where position matters
- Game boards: Chess squares, tic-tac-toe cells, Sudoku grids
The through-line: position-based access and known, stable collections.
Languages like Python (list), JavaScript (array), and Java (ArrayList) provide dynamic arrays that resize automatically. Under the hood, they allocate extra space and copy to larger arrays when needed—offering array-like random access with flexible sizing, at the cost of occasional O(n) resize operations (amortized O(1) for appends).
Linked Lists: The Flexible Chain
A linked list is a sequence of nodes where each node contains data and a reference (pointer) to the next node. Unlike arrays, nodes can be scattered anywhere in memory—they're connected by explicit links rather than physical adjacency.
The mental model:
Imagine a scavenger hunt where each clue leads you to the next location. You can't jump directly to clue #5; you must follow the chain from clue #1. But adding a new clue between existing ones is easy—just update the " next location" hints.
Key characteristics:
- Non-contiguous storage: Nodes can be anywhere in memory
- Dynamic size: Grows and shrinks by adding/removing nodes
- Node structure: Each node holds data + link(s) to neighbor(s)
- O(n) access: Must traverse from head to reach element i
- O(1) insertion/deletion: Once at the position, just update pointers
- •Dynamic sizing (grows/shrinks freely)
- •Insertions at beginning/middle
- •Deletions without shifting
- •Building other structures (stacks, queues)
- •Memory allocation flexibility
- •Random access by position
- •Cache efficiency (scattered nodes)
- •Memory overhead (pointer storage)
- •Binary search (no O(1) midpoint)
- •Reverse traversal (singly-linked)
Variants:
- Singly linked: Each node → next (one direction)
- Doubly linked: Each node ↔ prev and next (bidirectional)
- Circular: Last node → first node (forms a ring)
Real-world intuition:
Think of linked lists when you think of:
- Music playlists: Songs linked to "next song," easy to add/remove songs
- Browser history: Each page links to the previous/next visited
- Text editors (under the hood): Efficient insertion of characters
- Photo slideshows: Navigate forward/backward through photos
- Train cars: Each car connected to the next, easy to add/remove cars
The through-line: dynamic modification and sequential processing.
In practice, arrays often outperform linked lists due to cache efficiency—even for operations where linked lists have theoretically better complexity. Modern CPUs are optimized for sequential memory access. Always measure before assuming linked lists are faster.
Stacks: Last In, First Out (LIFO)
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle: the last element added is the first one removed. You can only add or remove from one end—the "top" of the stack.
The mental model:
Imagine a stack of dinner plates. You can only add a plate to the top or remove the top plate. The plate at the bottom was placed first but will be removed last. You can't pull a plate from the middle without removing everything above it.
Key characteristics:
- LIFO ordering: Last added, first removed
- Single access point: Operations only at the "top"
- Two primary operations: push (add to top), pop (remove from top)
- Auxiliary operation: peek (view top without removing)
- O(1) operations: Push, pop, and peek are all constant time
| Operation | Description | Time Complexity |
|---|---|---|
| push(item) | Add item to the top of the stack | O(1) |
| pop() | Remove and return the top item | O(1) |
| peek() / top() | Return the top item without removing | O(1) |
| isEmpty() | Check if the stack has no items | O(1) |
| size() | Return the number of items | O(1) |
Real-world intuition:
Think of stacks when you think of:
- Undo/Redo: Each action is pushed; undo pops the last action
- Browser back button: Pages visited are pushed; back pops the last page
- Function calls: Each call pushes a frame; return pops it
- Expression parsing: Operators and operands managed via stack
- Depth-first search: Nodes to visit are managed as a stack
- Balancing parentheses: Open parens push; close parens pop and match
The through-line: reversing order and nested/recursive structures.
Every programming language uses a stack to manage function calls. When function A calls function B, a stack frame for B is pushed. When B returns, its frame is popped, and control returns to A. Stack overflow errors occur when the call stack exceeds its size limit—typically from deep or infinite recursion.
Implementation note:
Stacks can be implemented using either arrays or linked lists:
- Array-based: Push increments index, pop decrements. Simple and cache-friendly.
- Linked list-based: Push adds to head, pop removes from head. Dynamic size.
Both provide O(1) operations. Array-based is more common due to simplicity and cache efficiency.
Queues: First In, First Out (FIFO)
A queue is a linear data structure that follows the First In, First Out (FIFO) principle: the first element added is the first one removed. You add at one end (the "back" or "rear") and remove from the other (the "front").
The mental model:
Imagine a line at a coffee shop. New customers join at the back; the person at the front is served first. It's fair—whoever arrived first gets served first. No cutting in line!
Key characteristics:
- FIFO ordering: First added, first removed
- Two access points: Add at rear, remove from front
- Two primary operations: enqueue (add to rear), dequeue (remove from front)
- Auxiliary operation: front/peek (view front without removing)
- O(1) operations: Enqueue and dequeue are constant time
| Operation | Description | Time Complexity |
|---|---|---|
| enqueue(item) | Add item to the rear of the queue | O(1) |
| dequeue() | Remove and return the front item | O(1) |
| front() / peek() | Return the front item without removing | O(1) |
| isEmpty() | Check if the queue has no items | O(1) |
| size() | Return the number of items | O(1) |
Real-world intuition:
Think of queues when you think of:
- Print jobs: Documents queued to printer in submission order
- Customer service: Calls answered in order received
- Task scheduling: CPU processes tasks in FIFO order (basic scheduling)
- Message queues: Messages processed in order sent
- Breadth-first search: Nodes to visit managed as a queue
- Buffering: Streaming data buffered in arrival order
The through-line: preserving order and processing in sequence.
Common queue variants include: Double-ended queue (deque) — add/remove from both ends; Priority queue — dequeue by priority, not FIFO order; Circular queue — efficient array-based implementation that wraps around.
Implementation note:
Queues can be implemented using:
- Linked list: Enqueue at tail, dequeue at head. Natural fit.
- Circular array: Front and rear pointers wrap around. Cache-friendly.
- Two stacks: Advanced technique for amortized O(1) operations.
Linked list implementation is conceptually cleaner; circular array is often faster in practice.
Comparing Arrays, Linked Lists, Stacks, and Queues
Now that we've surveyed each structure individually, let's compare them systematically. Understanding their differences helps you choose the right tool for each problem.
Organizational paradigm:
- Array/Linked List: General-purpose collections; any element accessible
- Stack: Restricted access; only top element accessible
- Queue: Restricted access; only front element removable, only rear addable
Stacks and queues are restricted interfaces on top of the underlying linear organization. They trade flexibility for clarity—by limiting what you can do, they make certain operations obvious and prevent misuse.
| Property | Array | Linked List | Stack | Queue |
|---|---|---|---|---|
| Access pattern | Any index | Sequential | Top only | Front/Rear |
| Ordering | By position | By links | LIFO | FIFO |
| Random access | O(1) | O(n) | Not applicable | Not applicable |
| Add to end | O(1)* | O(1)** | O(1) push | O(1) enqueue |
| Remove from end | O(1) | O(n)*** | O(1) pop | N/A |
| Add to front | O(n) | O(1) | N/A | N/A |
| Remove from front | O(n) | O(1) | N/A | O(1) dequeue |
| Memory usage | Compact | Overhead per node | Compact/Linked | Compact/Linked |
| Size flexibility | Fixed/Dynamic | Dynamic | Dynamic | Dynamic |
*Amortized O(1) for dynamic arrays **O(1) with tail pointer ***O(1) for doubly-linked lists
Key insight:
Arrays and linked lists are building blocks—they can implement any linear access pattern. Stacks and queues are behavioral abstractions—they define what operations are allowed, not how they're implemented.
In fact:
- A stack can be implemented using an array or a linked list
- A queue can be implemented using a linked list or a circular array
The stack/queue interface matters more than the underlying storage.
Think of arrays and linked lists as 'raw materials' and stacks/queues as 'finished products.' You can build stacks and queues from arrays or linked lists, just as you can build furniture from wood or metal. The choice of material (implementation) affects performance; the choice of product (interface) affects usage.
Choosing the Right Structure: A Decision Framework
With four structures to choose from, how do you decide? Here's a practical decision framework based on your access patterns and operations:
Step 1: Determine your access pattern
- Do you need to access elements by position? → Consider arrays
- Do you only access from the ends? → Consider stacks or queues
- Do you traverse sequentially with frequent modifications? → Consider linked lists
Step 2: Identify your primary operations
- Frequent index-based reads → Array
- Frequent insertions/deletions in the middle → Linked list
- Only add/remove from one end (LIFO) → Stack
- Add at one end, remove from other (FIFO) → Queue
| If you need... | Consider... |
|---|---|
| Fast access by index | Array |
| Binary search on sorted data | Array (sorted) |
| Frequent insertions at beginning | Linked List |
| Efficient insertions at arbitrary positions | Linked List |
| Undo/redo functionality | Stack |
| Matching/balancing (parens, tags) | Stack |
| Depth-first traversal | Stack |
| Task scheduling (FIFO order) | Queue |
| Breadth-first traversal | Queue |
| Buffer for streaming data | Queue |
| Both FIFO and LIFO capabilities | Deque (double-ended queue) |
Step 3: Consider practical factors
- Memory constraints: Arrays are more compact; linked lists have pointer overhead
- Cache performance: Arrays are cache-friendly; linked lists cause cache misses
- Size predictability: Arrays need size estimation; linked lists grow freely
- Language conveniences: Many languages have optimized array implementations
- •When in doubt, start with an array — It's the most efficient for most cases
- •Use linked list when insertions/deletions dominate and position doesn't matter
- •Use stack when you need LIFO semantics (last in, first out)
- •Use queue when you need FIFO semantics (first in, first out)
- •Measure before optimizing — Theoretical complexity isn't always practical reality
Real-World Applications: Where Each Structure Shines
Let's ground our understanding with concrete applications. For each structure, here are domains where it's the natural choice:
Arrays in the Wild:
- Image processing: Pixels stored as 2D array, accessed by (x, y)
- Database records: Rows as arrays of field values
- Scientific computing: Vectors, matrices, tensors
- Game development: Tile maps, entity pools, leaderboards
- Audio/video: Samples stored sequentially for playback
Linked Lists in the Wild:
- Memory allocators: Free blocks linked together
- LRU caches: Recently used items at head, evict from tail
- Polynomial representation: Terms linked by degree
- Music players: Playlists with flexible reordering
- Undo in advanced editors: Changes linked for navigation
- •Compilers: Expression parsing, syntax trees
- •Browsers: Back button navigation
- •Editors: Undo/redo operations
- •Algorithms: DFS, backtracking, recursion
- •Calculators: Postfix expression evaluation
- •Call centers: Recent call handling
- •Operating systems: Process scheduling
- •Web servers: Request handling
- •Networking: Packet buffers
- •Algorithms: BFS, level-order traversal
- •Message systems: Kafka, RabbitMQ
- •Print spoolers: Document queuing
Pattern recognition opportunity:
When you encounter these domains in problems or projects, you now have a starting point. See "fairness" or "ordering"? Think queue. See "reversal" or "matching"? Think stack. See "position-based" access? Think array. See "frequent modification"? Think linked list.
This domain-to-structure mapping is the beginning of pattern recognition—a skill that grows with practice and becomes increasingly automatic.
Every time you solve a problem, note which structure you used and why. Over time, you'll build an intuitive library: 'Problems that look like X usually need structure Y.' This library becomes your competitive advantage in both interviews and engineering.
KEEP LEARNING
Keep learning for free.
Read the complete lesson, save your notes and pick up where you left off with a free account. No card needed.