0
0
Data-structures-theoryHow-ToBeginner ยท 4 min read

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 StructureDescriptionUse Case
ArrayFixed-size ordered elementsFast access by index
Linked ListNodes linked dynamicallyEfficient insert/delete
StackLIFO orderUndo operations, expression evaluation
QueueFIFO orderTask scheduling, buffering
TreeHierarchical nodesFile systems, databases
GraphNodes with edgesSocial 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.