Data Structure & Algorithm
Data Structure & Algorithm
📦 1. Array
An array is like a box with many sections. Each section stores one value.
Example:
cpp
It stores 5 numbers.
You can use numbers[0] to get the first value (10).
✅ Using Array
cpp
cpp
struct Node {
int data;
Node* next;
};
Each node stores a value (data) and a pointer to the next node (next).
cpp
cpp
cpp
int stack[100];
int top = -1;
void push(int x) {
stack[++top] = x; // Add item
}
int pop() {
return stack[top--]; // Remove item
}
6. C++ Templates
Templates let us make functions or classes that work with any data type (like int, float, string).
cpp
✅ Example usage:
cpp
Stack<int> s1;
s1.push(100);
Stack<string> s2;
s2.push("Hello");
Runtime Memory Organization
When a program runs, it uses memory in different parts:
📌 Main parts:
🔁 Example:
cpp
void func() {
int x = 10; // stored in stack
}
int main() {
func(); // stack frame for func is created and then removed
}
📋 Queue (ADT)
A queue is like a line of people:
✨ Queue Operations:
🛠 Implementing Queue
✅ Using Linked List:
cpp
struct Node {
int data;
Node* next;
};
int queue[5];
int front = -1, rear = -1;
void enqueue(int x) {
if ((rear + 1) % 5 == front) {
// Queue is full
} else {
if (front == -1) front = 0;
rear = (rear + 1) % 5;
queue[rear] = x;
}
}
🎯 Uses of Queue
CPU Scheduling
Printing Tasks
Call Center Systems
Breadth First Search (BFS) in graphs
🔢 Priority Queue
A priority queue is a queue where each item has a priority.
cpp
1
/ \
3 5
/ \ /
4 6 9
🌳 Binary Tree
A binary tree is a tree where:
cpp
struct Node {
int data;
Node* left;
Node* right;
};
Simple Code:
cpp
cpp
int a = 10;
int &ref = a; // ref is another name for a
ref = 20; // now a = 20
cpp
🚫 Degenerate BST
A degenerate BST is like a linked list:
cpp
Node* rightRotate(Node* y) {
Node* x = y->left;
Node* T2 = x->right;
x->right = y;
y->left = T2;
return x;
}
2. Single Left Rotation (RR case)
cpp
Node* leftRotate(Node* x) {
Node* y = x->right;
Node* T2 = y->left;
y->left = x;
x->right = T2;
return y;
}
3. Left-Right (LR Rotation)
cpp
root->left = leftRotate(root->left);
return rightRotate(root);
4. Right-Left (RL Rotation)
cpp
root->right = rightRotate(root->right);
return leftRotate(root);
// LL Case
if (balance > 1 && key < node->left->data)
return rightRotate(node);
// RR Case
if (balance < -1 && key > node->right->data)
return leftRotate(node);
// LR Case
if (balance > 1 && key > node->left->data) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
// RL Case
if (balance < -1 && key < node->right->data) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
✅ Summary
Concept Simple Meaning
Traversal Ways to visit nodes in a tree
Delete in BST Remove node with proper rule
Reference Variable Another name for a variable
Degenerate BST Tree becomes like a linked list (bad)
AVL Tree A self-balancing BST
Rotations Fixes unbalanced trees
C++ AVL Insert Code Includes rotations for all 4 cases