1

Array - The Organized Shelf ๐Ÿ“š

Store multiple items in a numbered list

Simple Definition
An Array is a collection of items stored in consecutive memory locations, where each item can be accessed instantly using its index number.
Think of a parking lot with numbered spaces. Space 1, Space 2, Space 3... Each spot is right next to the other. If you know your parking number, you can walk directly to your car instantly. You don't need to search through all spaces - the numbering system lets you jump straight to the right location in one step.

The Bookshelf Analogy

Imagine a bookshelf with numbered slots: Slot 0, Slot 1, Slot 2, and so on. Each slot holds one book. You can instantly grab any book by knowing its slot number! "Get me the book in slot 3" - and you have it immediately.

An Array works exactly like this! It's a list where every item has a number (index), and you can access any item instantly if you know its position.

TV Channel Analogy

Your TV has channels numbered 1, 2, 3, 4... Press channel 5, and you instantly get that channel. The channels are stored in an array - each channel is at a specific numbered position, and the TV jumps directly to it!

Array Visualization

๐ŸŽฎ Game Inventory Array
0
๐Ÿ—ก๏ธ
1
๐Ÿ›ก๏ธ
2
๐Ÿงช
3
๐ŸŽ
4
๐Ÿ’ฐ
inventory[2] instantly gives us ๐Ÿงช (Health Potion)
Array in JavaScript
// Creating an array (like building a shelf)
let fruits = ["๐ŸŽ Apple", "๐ŸŒ Banana", "๐ŸŠ Orange", "๐Ÿ‡ Grapes"];

// Access items by index (position number)
console.log(fruits[0]);  // ๐ŸŽ Apple (first item, index 0)
console.log(fruits[2]);  // ๐ŸŠ Orange (third item, index 2)

// How many items? (array length)
console.log(fruits.length);  // 4

// Add item to the END (push)
fruits.push("๐Ÿ“ Strawberry");
console.log(fruits);  // ["๐ŸŽ Apple", "๐ŸŒ Banana", "๐ŸŠ Orange", "๐Ÿ‡ Grapes", "๐Ÿ“ Strawberry"]

// Remove item from the END (pop)
let lastFruit = fruits.pop();
console.log(lastFruit);  // ๐Ÿ“ Strawberry

// Change an item
fruits[1] = "๐Ÿฅญ Mango";  // Replace banana with mango!
console.log(fruits);  // ["๐ŸŽ Apple", "๐Ÿฅญ Mango", "๐ŸŠ Orange", "๐Ÿ‡ Grapes"]

// Loop through all items
console.log("My fruit collection:");
for (let i = 0; i < fruits.length; i++) {
    console.log(i + ": " + fruits[i]);
}

Array Key Points

  • Items are stored in numbered positions starting from 0
  • You can access ANY item instantly using its index
  • Arrays have a fixed size in some languages, but growable in JavaScript
  • Great for: Lists, collections, sequences of items
2

Stack - Last In, First Out ๐Ÿ“šโฌ†๏ธ

Like a stack of plates - you can only add or remove from the top

Simple Definition
A Stack is a data structure that follows LIFO (Last In, First Out) - the last item added is the first one to be removed.
Think of a backpack when packing for a trip. You put in your laptop first, then clothes on top, then snacks on top of that. When you arrive at your hotel, you take out the snacks first (last item in), then clothes, then laptop (first item in). You can't grab the laptop without removing everything above it - that's LIFO in action!

The Plate Stack

In a cafeteria, clean plates are stacked on top of each other. When you need a plate, you take the top one. When plates are washed, they're added to the top. You can't grab a plate from the middle or bottom without toppling the stack!

This is LIFO: Last In, First Out. The last plate added is the first one used!

The Undo Button

When you press "Undo" in a drawing app, it reverses your last action. Then the one before that. The computer keeps a stack of your actions, and undoes them in reverse order - the most recent action is undone first!

Stack Visualization: Book Stack

๐Ÿ“š Book Stack
Stack Rules:
โ€ข Push: Add to top
โ€ข Pop: Remove from top
โ€ข Peek: Look at top
Stack Implementation
// Stack class - like a stack of books
class Stack {
    constructor() {
        this.items = [];  // Empty stack
    }

    // Push: Add item to top
    push(item) {
        this.items.push(item);
        console.log(`๐Ÿ“š Pushed: ${item}`);
    }

    // Pop: Remove item from top
    pop() {
        if (this.isEmpty()) {
            console.log("โŒ Stack is empty!");
            return null;
        }
        let item = this.items.pop();
        console.log(`๐Ÿ“ค Popped: ${item}`);
        return item;
    }

    // Peek: Look at top item without removing
    peek() {
        if (this.isEmpty()) {
            return "Empty";
        }
        return this.items[this.items.length - 1];
    }

    // Check if stack is empty
    isEmpty() {
        return this.items.length === 0;
    }

    // Get size
    size() {
        return this.items.length;
    }
}

// Using the stack
let bookStack = new Stack();

bookStack.push("๐Ÿ“– Harry Potter");     // Bottom
bookStack.push("๐Ÿ“– The Hobbit");       
bookStack.push("๐Ÿ“– Charlotte's Web");  // Top

console.log("Top book: " + bookStack.peek());  // ๐Ÿ“– Charlotte's Web

bookStack.pop();  // Remove Charlotte's Web
bookStack.pop();  // Remove The Hobbit

console.log("Books left: " + bookStack.size());  // 1

// Real-world: Undo System
class UndoManager {
    constructor() {
        this.actions = new Stack();
    }

    doAction(action) {
        // Do the action
        console.log(`โœ… ${action}`);
        this.actions.push(action);
    }

    undo() {
        let lastAction = this.actions.pop();
        if (lastAction) {
            console.log(`โ†ฉ๏ธ Undid: ${lastAction}`);
        }
    }
}

Stack Key Points

  • LIFO: Last In, First Out
  • Only add/remove from the top
  • Great for: Undo/Redo, Browser back button, Expression evaluation
3

Queue - First In, First Out ๐Ÿšถโ€โ™‚๏ธ๐Ÿšถโ€โ™€๏ธ

Like a line at a store - first person in line is first to be served

Simple Definition
A Queue is a data structure that follows FIFO (First In, First Out) - the first item added is the first one to be removed.
Think of a water slide at a water park. The first person to climb the stairs and get in line is the first one to slide down. New arrivals keep joining at the back of the line. Everyone moves forward as people slide down, maintaining the exact order they arrived. Fair and orderly - first to arrive, first to enjoy!

The Store Line

When you stand in line at a store, the person who arrived first gets served first. New people join at the back of the line. You can't cut in front - that would be unfair!

This is FIFO: First In, First Out. The first person in line is the first one out!

The Restaurant Waitlist

When a popular restaurant is full, they put you on a waitlist. The first family that called gets the first available table. New callers are added to the end. Everyone is served in the order they arrived - fair and organized!

Queue Visualization: Waiting Line

๐ŸŽข Ride Queue
๐Ÿšช FRONT (Dequeue here)
๐Ÿšถ BACK (Enqueue here)
Queue Rules:
โ€ข Enqueue: Add to back
โ€ข Dequeue: Remove from front
โ€ข Fair ordering!
Queue Implementation
// Queue class - like a line of people
class Queue {
    constructor() {
        this.items = [];  // Empty queue
    }

    // Enqueue: Add to back (end of line)
    enqueue(item) {
        this.items.push(item);
        console.log(`๐Ÿšถ ${item} joined the line`);
    }

    // Dequeue: Remove from front (front of line)
    dequeue() {
        if (this.isEmpty()) {
            console.log("โŒ No one in line!");
            return null;
        }
        let item = this.items.shift();  // shift() removes from front
        console.log(`โœ… ${item} is being served!`);
        return item;
    }

    // Peek: Look at who's first in line
    peek() {
        if (this.isEmpty()) {
            return "No one in line";
        }
        return this.items[0];
    }

    isEmpty() {
        return this.items.length === 0;
    }

    size() {
        return this.items.length;
    }
}

// Using the queue
let rideQueue = new Queue();

rideQueue.enqueue("๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง The Smith Family");  // First in line
rideQueue.enqueue("๐Ÿ‘ฆ Billy");
rideQueue.enqueue("๐Ÿ‘ต Grandma Jones");
rideQueue.enqueue("๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ฆ The Parkers");   // Last in line

console.log("Next to ride: " + rideQueue.peek());  // Smith Family

rideQueue.dequeue();  // Smith Family rides!
rideQueue.dequeue();  // Billy rides!

console.log("Still waiting: " + rideQueue.size() + " groups");  // 2

// Real-world: Print Queue
class PrintQueue {
    constructor() {
        this.documents = new Queue();
    }

    addDocument(doc) {
        this.documents.enqueue(doc);
        console.log(`๐Ÿ“„ ${doc} added to print queue`);
    }

    printNext() {
        let doc = this.documents.dequeue();
        if (doc) {
            console.log(`๐Ÿ–จ๏ธ Printing: ${doc}`);
        }
    }
}

Queue Key Points

  • FIFO: First In, First Out
  • Add to back, remove from front
  • Great for: Printer queues, customer service, task scheduling
4

Linked List - Connected Nodes ๐Ÿ”—

Items that link to each other like a treasure hunt chain

Simple Definition
A Linked List is a data structure where each item (node) contains data and a reference (link) to the next item, forming a chain-like sequence.
Think of a scavenger hunt with numbered envelopes. You open envelope #1 and it says "Look under the sofa for envelope #2." Under the sofa, envelope #2 says "Check the refrigerator for envelope #3." Each envelope contains a clue AND directions to the next one. They're scattered throughout the house but linked together by the references inside each envelope.

The Treasure Hunt

In a treasure hunt, you find a clue that says "Look under the oak tree." Under the oak tree, you find another clue: "Check the mailbox." The mailbox clue says: "Dig behind the garage." Each clue points to the next location - they're linked together!

A Linked List works like this! Each item (node) contains data AND a pointer to the next item. You can only find item 3 by going through items 1 and 2 first.

Train Cars

A train is made of connected cars. Each car is linked to the next one. To reach the last car, you must pass through all the cars before it. You can add a new car anywhere by simply connecting it between two existing cars!

Linked List Visualization

๐ŸŽ
๐ŸŒ
๐ŸŠ
NULL
HEAD
Start of list
Points to first node
NODE
Data + Next pointer
Contains item and link
NULL
End of list
Nothing comes after
Linked List Implementation
// Node class - each item in the list
class Node {
    constructor(data) {
        this.data = data;    // The actual data (like ๐ŸŽ)
        this.next = null;   // Link to next node (starts empty)
    }
}

// LinkedList class - manages the chain
class LinkedList {
    constructor() {
        this.head = null;   // Start of list (empty at first)
        this.size = 0;
    }

    // Add to beginning
    addFirst(data) {
        let newNode = new Node(data);
        newNode.next = this.head;  // New node points to old first node
        this.head = newNode;          // Head now points to new node
        this.size++;
        console.log(`โž• Added ${data} to front`);
    }

    // Add to end
    addLast(data) {
        let newNode = new Node(data);
        
        if (!this.head) {
            this.head = newNode;  // First item
        } else {
            let current = this.head;
            while (current.next) {   // Walk to the end
                current = current.next;
            }
            current.next = newNode;  // Last node now points to new node
        }
        this.size++;
        console.log(`โž• Added ${data} to back`);
    }

    // Print the list
    print() {
        let current = this.head;
        let result = "HEAD -> ";
        
        while (current) {
            result += current.data + " -> ";
            current = current.next;
        }
        result += "NULL";
        
        console.log(result);
    }

    // Remove first item
    removeFirst() {
        if (!this.head) {
            console.log("List is empty!");
            return;
        }
        let removed = this.head.data;
        this.head = this.head.next;  // Head moves to next node
        this.size--;
        console.log(`โž– Removed ${removed} from front`);
    }
}

// Using the linked list
let fruitList = new LinkedList();

fruitList.addLast("๐ŸŽ Apple");     // HEAD -> ๐ŸŽ -> NULL
fruitList.addLast("๐ŸŒ Banana");    // HEAD -> ๐ŸŽ -> ๐ŸŒ -> NULL
fruitList.addFirst("๐Ÿ‡ Grape");   // HEAD -> ๐Ÿ‡ -> ๐ŸŽ -> ๐ŸŒ -> NULL

fruitList.print();  // Shows: HEAD -> ๐Ÿ‡ -> ๐ŸŽ -> ๐ŸŒ -> NULL

fruitList.removeFirst();  // Removes ๐Ÿ‡
fruitList.print();  // Shows: HEAD -> ๐ŸŽ -> ๐ŸŒ -> NULL

console.log("Total fruits: " + fruitList.size);  // 2

Linked List Key Points

  • Each node contains data + pointer to next node
  • Adding/removing in the middle is fast (just change links)
  • Finding an item is slow (must start from head and follow links)
  • Can grow and shrink easily - no fixed size!

Data Structures Comparison

Structure Access Add/Remove Order Best For
Array Fast Slow Indexed Fixed collections, fast lookups
Stack Top only Fast LIFO Undo, back button, parsing
Queue Ends only Fast FIFO Print jobs, processing lines
Linked List Slow Fast Sequential Dynamic size, frequent inserts

Data Structures Mastery Check

Test your understanding of Arrays, Stacks, Queues, and Linked Lists!