Types of Data Structures: Overview and Examples
Data structures organize and store data efficiently. Common types include
arrays for ordered elements, linked lists for dynamic sequences, stacks and queues for controlled access, and trees and graphs for hierarchical or networked data.Syntax
Each data structure has a typical way to create and use it:
- Array: A fixed-size list of elements accessed by index.
- Linked List: Nodes linked by pointers, allowing dynamic size.
- Stack: Last-in, first-out (LIFO) structure with push/pop operations.
- Queue: First-in, first-out (FIFO) structure with enqueue/dequeue operations.
- Tree: Hierarchical nodes with parent-child relationships.
- Graph: Nodes connected by edges, representing networks.
python
array = [1, 2, 3] class Node: def __init__(self, value): self.value = value self.next = None stack = [] # use list as stack from collections import deque queue = deque() class TreeNode: def __init__(self, value): self.value = value self.children = [] class Graph: def __init__(self): self.nodes = {} def add_edge(self, u, v): self.nodes.setdefault(u, []).append(v) self.nodes.setdefault(v, []).append(u)
Example
This example shows how to use a stack and a queue to add and remove items:
python
from collections import deque # Stack example (LIFO) stack = [] stack.append('a') stack.append('b') print('Stack pop:', stack.pop()) # removes 'b' # Queue example (FIFO) queue = deque() queue.append('a') queue.append('b') print('Queue dequeue:', queue.popleft()) # removes 'a'
Output
Stack pop: b
Queue dequeue: a
Common Pitfalls
Common mistakes include:
- Using arrays when dynamic size is needed (use linked lists instead).
- Confusing stack and queue order rules.
- Not handling empty structures before removing elements, causing errors.
- Ignoring the difference between trees and graphs in structure and traversal.
python
stack = [] # Wrong: popping from empty stack causes error # print(stack.pop()) # IndexError # Right: check before popping if stack: print(stack.pop()) else: print('Stack is empty')
Output
Stack is empty
Quick Reference
| Data Structure | Description | Use Case |
|---|---|---|
| Array | Fixed-size ordered elements | Fast access by index |
| Linked List | Nodes linked dynamically | Efficient insert/delete |
| Stack | LIFO order | Undo operations, expression evaluation |
| Queue | FIFO order | Task scheduling, buffering |
| Tree | Hierarchical nodes | File systems, databases |
| Graph | Nodes with edges | Social networks, maps |
Key Takeaways
Choose data structures based on how you need to access and modify data.
Arrays are simple but fixed size; linked lists allow flexible size.
Stacks and queues control order of data processing differently.
Trees organize data hierarchically; graphs model complex relationships.
Always check for empty structures before removing elements to avoid errors.