Linear Structures

Back

Loading concept...

πŸš‚ The Train Station of Data: Linear Structures

Imagine you’re running a magical train station where different types of trains carry passengers in a straight line. Each train type has its own special way of loading and unloading people. Welcome to the world of Linear Data Structures!


🎯 What Are Linear Data Structures?

Think of a line of kids waiting for ice cream. Each kid stands behind another - one after one. That’s β€œlinear” - things arranged in a straight line order.

In computers, we store data the same way - one piece after another, like beads on a string!

graph TD A["πŸ”΅ First"] --> B["🟒 Second"] B --> C["🟑 Third"] C --> D["πŸ”΄ Fourth"]

πŸ“¦ Abstract Data Types (ADT)

What’s an ADT?

Imagine a vending machine. You press a button, and a snack comes out. You don’t need to know HOW the machine works inside - you just know WHAT it does!

Abstract Data Type = What it does, not how it works

You Know You Don’t Need to Know
Press button β†’ Get snack How gears move inside
Put money in β†’ It counts How coins are sorted

Real Example: A List is an ADT. It says:

  • βœ… Add items
  • βœ… Remove items
  • βœ… Find items
  • ❓ How? That’s decided later!

πŸ“Š Arrays: The Numbered Lockers

The Story

Picture a row of numbered lockers at school - Locker 0, Locker 1, Locker 2… Each locker holds ONE thing, and you find it using its number!

β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”
β”‚  🍎 β”‚  🍌 β”‚  πŸ‡ β”‚  🍊 β”‚  πŸ“ β”‚
β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€
β”‚  0  β”‚  1  β”‚  2  β”‚  3  β”‚  4  β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜

Key Features

Feature What It Means
Fixed Size Buy 10 lockers, get exactly 10
Indexed Each spot has a number (0, 1, 2…)
Fast Access Say β€œLocker 3” β†’ Get item instantly!
Same Type All lockers hold same kind of stuff

Simple Code Example

# Create array of fruits
fruits = ["apple", "banana",
          "grape", "orange"]

# Get fruit at position 2
print(fruits[2])  # grape

# Change fruit at position 0
fruits[0] = "mango"

⚑ Speed

  • Finding item by number: Super fast! ⚑
  • Adding item at end: Fast!
  • Adding item in middle: Slow 🐒 (must shift everything!)

🎈 Dynamic Arrays: The Magic Expanding Backpack

The Story

What if your backpack could grow bigger when you need more space? That’s a Dynamic Array!

Start with a small bag. When it’s full, POOF - it doubles in size automatically!

graph LR A["πŸ“¦ Size 4"] -->|Full!| B["πŸ“¦πŸ“¦ Size 8"] B -->|Full!| C["πŸ“¦πŸ“¦πŸ“¦πŸ“¦ Size 16"]

How It Works

  1. Start small (say, space for 4 items)
  2. Fill it up (add 4 items)
  3. Need more? Create bigger array (usually 2x)
  4. Copy everything to new, bigger space
  5. Continue adding!

Simple Example

# Python list = dynamic array!
backpack = []

# Keep adding - it grows!
backpack.append("book")
backpack.append("pencil")
backpack.append("snack")
backpack.append("toy")
# Still adding? No problem!
backpack.append("water")

Array vs Dynamic Array

Regular Array Dynamic Array
Fixed size forever Grows when needed
β€œ5 spots only!” β€œAdd as many as you want!”
Can’t add more Handles overflow

πŸ”€ Strings: The Letter Necklace

The Story

Imagine making a friendship bracelet with letter beads. Each bead is ONE letter, and together they spell a word!

"HELLO" =
β”Œβ”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”
β”‚ H β”‚ E β”‚ L β”‚ L β”‚ O β”‚
β””β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”˜
  0   1   2   3   4

A String is just an array of characters (letters, numbers, symbols)!

Why Strings Are Special

  • πŸ“ Store names: "Alice"
  • πŸ’¬ Store messages: "Hello World!"
  • πŸ”’ Even numbers as text: "123"

Simple Example

# Create a string
name = "HELLO"

# Get letter at position 1
print(name[1])  # E

# Count letters
print(len(name))  # 5

βœ‚οΈ String Operations: Playing with Words

Common Operations

Think of string operations like word games!

1. Concatenation (Joining)

Stick two strings together like connecting train cars!

first = "Hello"
second = "World"
together = first + " " + second
# "Hello World"

2. Finding Length

Count the beads on your bracelet!

word = "Python"
print(len(word))  # 6

3. Slicing (Cutting)

Take a piece of the string!

text = "RAINBOW"
piece = text[0:4]  # "RAIN"

4. Finding

Where is this letter hiding?

word = "BANANA"
pos = word.find("N")  # 2

5. Replacing

Swap letters like trading cards!

old = "cat"
new = old.replace("c", "b")
# "bat"

Operations Summary

Operation What It Does Example
+ Join strings "Hi" + "!" β†’ "Hi!"
len() Count letters len("abc") β†’ 3
[i] Get one letter "dog"[0] β†’ "d"
[a:b] Get substring "hello"[1:4] β†’ "ell"
find() Locate letter "cat".find("a") β†’ 1

πŸ”— Linked Lists: The Paper Chain

The Story

Remember making paper chains for decorations? Each link holds onto the next one. If you want to find the 5th link, you start at the first and follow the chain!

graph LR A["πŸ“§ Data + β†’"] --> B["πŸ“§ Data + β†’"] B --> C["πŸ“§ Data + β†’"] C --> D["πŸ“§ Data + βœ–"]

How It’s Different from Arrays

Array (Lockers) Linked List (Chain)
Items side by side Items connected by links
Go directly to any Follow chain from start
Fixed size Grows easily
Fast random access Fast insert/delete

The Node: Building Block

Each piece of the chain is called a Node. It has:

  • πŸ“¦ Data (the actual value)
  • ➑️ Pointer (arrow to next node)
Node = [ Data | Next β†’ ]

➑️ Singly Linked Lists: One-Way Street

The Story

Imagine a one-way street. Cars can only go forward! Each car knows only about the car in front of it.

graph LR HEAD["HEAD 🏁"] --> A["10"] A --> B["20"] B --> C["30"] C --> NULL["NULL β›”"]

Parts of Singly Linked List

  • HEAD: The starting point (first node)
  • Nodes: Each box with data
  • NULL: The end (no more nodes)

Simple Operations

Adding at Beginning (Fast! ⚑)

New node β†’ points to old HEAD
HEAD now points to new node

Before: HEAD β†’ [10] β†’ [20] β†’ NULL
After:  HEAD β†’ [5] β†’ [10] β†’ [20] β†’ NULL

Finding a Value (Walk the chain 🚢)

Start at HEAD, check each node until found!

Code Example

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class SinglyLinkedList:
    def __init__(self):
        self.head = None

    def add_front(self, data):
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node

Pros and Cons

βœ… Good ❌ Not So Good
Easy to add at front Can’t go backwards
Grows as needed Must start from HEAD
Simple structure No direct access

↔️ Doubly Linked Lists: Two-Way Street

The Story

Now imagine a two-way street! Each car knows about the car in front AND behind. You can go forward OR backward!

graph LR NULL1["NULL β›”"] --> A A["10"] --> B["20"] B --> A B --> C["30"] C --> B C --> NULL2["NULL β›”"]

The Double Node

Each node now has THREE parts:

  • ⬅️ Previous pointer (who’s behind me?)
  • πŸ“¦ Data (the value)
  • ➑️ Next pointer (who’s ahead?)
Node = [ ← Prev | Data | Next β†’ ]

Compared to Singly Linked

Singly Linked Doubly Linked
One direction β†’ Both directions ↔
One pointer Two pointers
Less memory More memory
Can’t go back Can go back!

Simple Visualization

HEAD                           TAIL
 ↓                              ↓
NULL ← [A] ↔ [B] ↔ [C] ↔ [D] β†’ NULL

Code Example

class DNode:
    def __init__(self, data):
        self.data = data
        self.prev = None
        self.next = None

class DoublyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

When to Use What?

Use Singly When… Use Doubly When…
Memory is limited Need to go backwards
Only forward access Delete from middle often
Simple is better Have HEAD and TAIL

🎯 Quick Comparison: All Linear Structures

Structure Access Insert Start Insert End Memory
Array ⚑ Fast 🐒 Slow 🐒 Slow Fixed
Dynamic Array ⚑ Fast 🐒 Slow ⚑ Fast* Grows
Singly Linked 🐒 Slow ⚑ Fast 🐒 Slow Grows
Doubly Linked 🐒 Slow ⚑ Fast ⚑ Fast Grows

*Fast most of the time, slow when resizing


🌟 Summary: Your New Friends

You’ve just met some amazing data structures:

  1. πŸ“¦ Arrays - Numbered lockers, fast access
  2. 🎈 Dynamic Arrays - Magic growing backpacks
  3. πŸ”€ Strings - Letter necklaces
  4. βœ‚οΈ String Ops - Word games and tricks
  5. πŸ”— Linked Lists - Paper chains
  6. ➑️ Singly Linked - One-way streets
  7. ↔️ Doubly Linked - Two-way streets

Each one is special and perfect for different jobs. Now you know when to use which train at your data station! πŸš‚


Remember: The best programmers don’t memorize everything - they understand WHY things work. You’re already on your way! πŸš€

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.