Data Structures & Algorithms Linked Lists
💡
Exercise 61

Linked List Basics 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

A Linked List is a data structure where each element (node) contains data AND a pointer to the next node. Unlike arrays, elements aren't stored next to each other in memory! 🔗

💡 Think of it like this: Imagine a treasure hunt. Each clue has a piece of paper with a message AND directions to the next clue. You follow the chain: Clue 1 → Clue 2 → Clue 3 → End. That's a linked list!

💭 Go for it! Apply the approach above in your own code. If you get stuck, use the hint below! 🔥

Array vs Linked List:

  • Insert/Delete at beginning: Linked List O(1) vs Array O(n)
  • Access by index: Array O(1) vs Linked List O(n)
  • Dynamic size: Linked Lists grow/shrink easily, no resizing needed
  • Memory: Linked Lists use extra memory for pointers

Common linked list techniques you'll use in interviews:

  • 🐢🐇 Fast & Slow pointers: Detect cycles, find middle
  • ↩️ Reverse: Flip all the arrows (3 pointer technique)
  • 🔀 Merge: Combine two sorted lists
  • 👻 Dummy node: Simplify edge cases (empty list, single element)
📋 Instructions
Create a linked list with values 1 → 2 → 3 → 4 → 5. Then traverse it and print each value on a separate line.
Create head = ListNode(1), then chain .next nodes. Traverse with a while loop: while current is not None, print val, move to current.next.
⚠️ Try solving it yourself first — you'll learn more!
# A Node has data + a pointer to next
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# Building: 1 → 2 → 3 → None
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)

# Traversal:
current = head
while current:
    print(current.val, end=' → ')
    current = current.next
# Output: 1 → 2 → 3 →
🧪 Test Cases
Input
Run your code
Expected
1 2 3 ...
Expected output (5 lines)
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.