Key Takeaways: A Linked List is a linear data structure where elements are not stored in contiguous memory locations. Instead, each element (called a Node) points to the next one, forming a chain.
After mastering Arrays, it's time to look at the next major data structure: the Linked List.
Arrays are great, but they have a massive weakness: inserting or deleting items in the middle is extremely slow because you have to shift everything over. Linked Lists solve this exact problem!
A Linked List is a chain of items. Each item in the chain is called a Node.
Every Node contains two important pieces of information:
The first Node is called the Head. The last Node's pointer points to null (meaning the end of the line).
Imagine a scavenger hunt. You are given a clue (Data). At the bottom of the clue, it tells you exactly where to find the next clue (Next Pointer). You go to that location, find the next clue, and repeat until you reach the final destination!
A Linked List: Nodes scattered in memory, connected by pointers.
Why use a Linked List instead of an Array? Let's compare them!
O(n). Very slow. If you insert an item at the beginning, you must shift every other item down.O(1). Lightning fast! If you want to insert a new Node, you just change two pointers to link it into the chain. No shifting required!O(1). Lightning fast. You can instantly open arr[5].O(n). Very slow. To find the 5th item, you must start at the Head and follow the pointers one by one until you reach it.There are three main variations of Linked Lists you will encounter:
null. Instead, it points back to the Head, creating an infinite loop!Here is how you would create a simple Singly Linked List in Python.
First, we create a Node class. Then, we link them together!
# 1. Create the Node Class class Node: def __init__(self, data): self.data = data self.next = None # Initially, it doesn't point to anything # 2. Create individual Nodes head = Node(10) node2 = Node(20) node3 = Node(30) # 3. Link the Nodes together to form a chain! head.next = node2 node2.next = node3 # 4. Traverse (Loop through) the Linked List current = head while current is not None: print(current.data) current = current.next
What are the two main components of a standard Linked List Node?
Why is inserting an element at the beginning of a Linked List faster than an Array?