A Linked List is a linear data structure where elements (called nodes) are stored dynamically and connected using pointers.
Structure of a Node (C code): struct Node { int data; struct Node* next; };
1. Singly Linked List
Each node points to the next node.
[10 | next] -> [20 | next] -> [30 | next] -> NULL
2. Doubly Linked List
Each node has two pointers: one to the next node and one to the previous node.
NULL <- [10 | prev,next] <-> [20 | prev,next] <-> [30 | prev,next] -> NULL
3. Circular Linked List
The last node points back to the first node.
[10] -> [20] -> [30] -+
^-------------------+
- Dynamic size (no fixed capacity).
- Efficient insertions/deletions if pointer is known.
- Sequential access (O(n) search).
- Extra memory required for pointers.
A Binary Search Tree is a hierarchical structure where each node has at most two children, and values are arranged so that:
- Left child < Parent
- Right child > Parent
Structure of a Node (C code): struct Node { int data; struct Node* left; struct Node* right; };
50
/ \
30 70
/ \ / \
20 40 60 80
- Search → O(log n) average, O(n) worst case.
- Insert → Place value according to BST rules.
- Delete → Three cases:
- Node is a leaf → remove directly.
- Node has one child → replace with child.
- Node has two children → replace with inorder successor or predecessor.
Tree Traversals:
- Inorder (L → Root → R) → Produces sorted order.
- Preorder (Root → L → R).
- Postorder (L → R → Root).
- Level Order (Breadth-First Search).
Terminology:
- Vertex (V): a node in the graph.
- Edge (E): a connection between two vertices.
- Directed Graph: edges have direction (A → B).
- Undirected Graph: edges have no direction (A -- B).
-
Adjacency Matrix
A 2D array where matrix[i][j] = 1 if there is an edge from i to j. -
Adjacency List
Each vertex stores a list of adjacent vertices.
A -- B
| |
C -- D
- Social networks (users as vertices, friendships as edges).
- Maps and navigation (cities as vertices, roads as edges).
- Computer networks, dependency resolution, pathfinding.
Sorting is the process of arranging elements in a specific order (ascending or descending).
One of the simplest sorting algorithms is Bubble Sort.
Definition:
Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order. This process continues until the array is sorted.
- Start at the first element.
- Compare the current element with the next one.
- If they are in the wrong order, swap them.
- Move to the next pair and repeat until the end of the array.
- Repeat the entire process for
n-1
passes or until no swaps are needed.
Initial Array:
Pass 1 → `[3, 5, 4, 2, 8]`
Pass 2 → `[3, 4, 2, 5, 8]`
Pass 3 → `[3, 2, 4, 5, 8]`
Pass 4 → `[2, 3, 4, 5, 8]` ===> Sorted
- Best Case: O(n) (already sorted, with optimized check)
- Worst Case: O(n²)
- Space Complexity: O(1) (in-place sorting)