An array stores items in a contiguous block of memory. A linked list stores items as nodes scattered across memory, each pointing to the next node.
[data|next] -> [data|next] -> [data|next] -> None
head node 1 node 2
Each node contains:
The list ends when next is None.
Each node has a data field and a next pointer. The head points to the first node. The last node points to None.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data): # Insert at front: O(1)
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def find(self, target): # Traverse: O(n)
current = self.head
while current:
if current.data == target:
return current
current = current.next
return None
def delete(self, target): # Traverse + reconnect: O(n)
current = self.head
prev = None
while current:
if current.data == target:
if prev: prev.next = current.next
else: self.head = current.next
return True
prev, current = current, current.next
return False
A binary tree is a hierarchical structure where each node has at most two children: left and right.
A BST is a binary tree where for every node:
Tree traversal β In-order:
def inorder(node):
if node:
inorder(node.left) # Visit left
print(node.data) # Visit node
inorder(node.right) # Visit right
# Result: sorted order!
def find(node, target):
current = node
while current:
if current.data == target: return True
elif target < current.data: current = current.left
else: current = current.right
return False