Data Structures
Learn how computers organize and store information efficiently
Array - The Organized Shelf ๐
Store multiple items in a numbered list
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
inventory[2] instantly gives us ๐งช (Health Potion)
// 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
Stack - Last In, First Out ๐โฌ๏ธ
Like a stack of plates - you can only add or remove from the top
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
โข Push: Add to top
โข Pop: Remove from top
โข Peek: Look at top
// 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
Queue - First In, First Out ๐ถโโ๏ธ๐ถโโ๏ธ
Like a line at a store - first person in line is first to be served
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
โข Enqueue: Add to back
โข Dequeue: Remove from front
โข Fair ordering!
// 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
Linked List - Connected Nodes ๐
Items that link to each other like a treasure hunt chain
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
// 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!