Lesson 18 • Advanced

Data Structures

45 minutes
Advanced Data Structures

🏗️ What are Data Structures?

Data structures are specialized ways of organizing and storing data to enable efficient access and modification. Different structures are optimized for different operations.

Why Data Structures Matter
  • Efficiency: Right structure = faster operations
  • Organization: Model real-world relationships
  • Problem-solving: Some problems require specific structures
  • Foundation: Essential for advanced programming

Stack (LIFO - Last In, First Out)

A Stack is like a stack of plates - you add (push) and remove (pop) from the top only. The last item added is the first one removed.

Stack Operations:

  • Push: Add element to top
  • Pop: Remove element from top
  • Peek: Look at top element without removing
  • IsEmpty: Check if stack is empty
Example: Stack Implementation
Algorithm StackExample

var stack[10]  # Array to hold stack elements
var top = -1      # Points to top element (-1 means empty)

# Push operation
Procedure Push(value)
    top = top + 1
    stack[top] = value
    Print "Pushed:", value
Endprocedure

# Pop operation
Function Pop()
    If top == -1 Then
        Print "Stack is empty!"
        Return -1
    Else
        var value = stack[top]
        top = top - 1
        Return value
    Endif
Endfunction

# Test the stack
Print "=== STACK OPERATIONS ==="
Print ""

Push(10)
Push(20)
Push(30)

Print ""
Print "Popping elements:"
Print "Popped:", Pop()  # Returns 30 (last in)
Print "Popped:", Pop()  # Returns 20
Print "Popped:", Pop()  # Returns 10 (first in)

Endalgorithm
Output
=== STACK OPERATIONS === Pushed: 10 Pushed: 20 Pushed: 30 Popping elements: Popped: 30 Popped: 20 Popped: 10

Stack Use Cases:

  • Undo/Redo functionality
  • Browser back button
  • Function call stack
  • Expression evaluation

Queue (FIFO - First In, First Out)

A Queue is like a line of people - first person in line is first to be served. Add to the back (enqueue), remove from the front (dequeue).

Queue Operations:

  • Enqueue: Add element to back
  • Dequeue: Remove element from front
  • Peek: Look at front element
  • IsEmpty: Check if queue is empty
Example: Queue Implementation
Algorithm QueueExample

var queue[10]
var front = 0
var rear = -1
var size = 0

# Enqueue operation
Procedure Enqueue(value)
    rear = rear + 1
    queue[rear] = value
    size = size + 1
    Print "Enqueued:", value
Endprocedure

# Dequeue operation
Function Dequeue()
    If size == 0 Then
        Print "Queue is empty!"
        Return -1
    Else
        var value = queue[front]
        front = front + 1
        size = size - 1
        Return value
    Endif
Endfunction

# Test the queue
Print "=== QUEUE OPERATIONS ==="
Print ""

Enqueue(10)
Enqueue(20)
Enqueue(30)

Print ""
Print "Dequeuing elements:"
Print "Dequeued:", Dequeue()  # Returns 10 (first in)
Print "Dequeued:", Dequeue()  # Returns 20
Print "Dequeued:", Dequeue()  # Returns 30 (last in)

Endalgorithm
Output
=== QUEUE OPERATIONS === Enqueued: 10 Enqueued: 20 Enqueued: 30 Dequeuing elements: Dequeued: 10 Dequeued: 20 Dequeued: 30

Queue Use Cases:

  • Print job queue
  • Customer service lines
  • Task scheduling
  • Message queues

Real-World Applications

Task Manager with Queue

Example: Task Queue System
Algorithm TaskQueue

var tasks[20]
var taskFront = 0
var taskRear = -1
var taskCount = 0

Procedure AddTask(taskName)
    taskRear = taskRear + 1
    tasks[taskRear] = taskName
    taskCount = taskCount + 1
    Print "✅ Task added:", taskName
Endprocedure

Function ProcessTask()
    If taskCount == 0 Then
        Return "No tasks"
    Else
        var task = tasks[taskFront]
        taskFront = taskFront + 1
        taskCount = taskCount - 1
        Return task
    Endif
Endfunction

Print "=== TASK MANAGER ==="
Print ""

# Add tasks
AddTask("Write report")
AddTask("Send emails")
AddTask("Review code")

Print ""
Print "Processing tasks..."
Print "Working on:", ProcessTask()
Print "Working on:", ProcessTask()
Print "Working on:", ProcessTask()

Endalgorithm

Undo System with Stack

Example: Undo/Redo System
Algorithm UndoSystem

var actions[20]
var actionTop = -1

Procedure DoAction(action)
    actionTop = actionTop + 1
    actions[actionTop] = action
    Print "Action:", action
Endprocedure

Function Undo()
    If actionTop == -1 Then
        Return "Nothing to undo"
    Else
        var lastAction = actions[actionTop]
        actionTop = actionTop - 1
        Return "Undoing: " + lastAction
    Endif
Endfunction

Print "=== TEXT EDITOR ==="
Print ""

DoAction("Type 'Hello'")
DoAction("Add space")
DoAction("Type 'World'")

Print ""
Print Undo()  # Undo "Type 'World'"
Print Undo()  # Undo "Add space"

Endalgorithm

🔗 Linked List Concept

A Linked List is a sequence of nodes where each node contains data and a reference (link) to the next node. Unlike arrays, elements aren't stored contiguously in memory.

Linked List vs. Array
Feature Array Linked List
Access Fast (direct index) Slow (must traverse)
Insert/Delete Slow (shift elements) Fast (change links)
Size Fixed Dynamic

Conceptual Linked List

# Conceptual representation (simplified)
# Node structure: [data | next]

# List: 10 → 20 → 30 → null
#       ^         ^        ^
#      head     middle    end

📊 Choosing the Right Structure

Structure Order Best For
Array Indexed Random access, fixed size collections
Stack LIFO Undo operations, backtracking
Queue FIFO Task scheduling, breadth-first traversal
Linked List Sequential Frequent insertions/deletions

Key Takeaways

  • ✅ Data structures organize data for efficient operations
  • Stack (LIFO): Last in, first out - undo, backtracking
  • Queue (FIFO): First in, first out - task scheduling
  • Linked List: Dynamic size, efficient insertions
  • ✅ Choose structure based on your needs
  • ✅ Each structure has trade-offs (speed vs. flexibility)
  • ✅ Arrays can implement stacks and queues

💪 Practice Exercises

Try These Exercises

Exercise 1: Balanced Parentheses
Use a stack to check if parentheses in an expression are balanced: "(())" is valid, "(()" is not.
Exercise 2: Print Queue Simulator
Simulate a printer queue where documents are printed in order they were submitted.
Exercise 3: Browser History
Implement browser back/forward using two stacks (back history and forward history).
Exercise 4: Playlist Manager
Create a music playlist using a queue - add songs to queue, play next song, show remaining songs.
Amazing Progress!
You now understand fundamental data structures! In the next lesson, we'll explore algorithm design patterns to solve problems efficiently.