Module 2
Module 2
1. Stacks
1.1 Introduction
A stack is a linear data structure that follows the Last In First Out (LIFO) principle. The element
added last is removed first. It has two primary operations:
int stack[MAX];
if (top == MAX - 1) {
printf("Stack Overflow\n");
return;
stack[++top] = item;
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
• Reversing strings
2. Queues
2.1 Introduction
A queue is a linear data structure that follows the First In First Out (FIFO) principle. The element
inserted first is removed first. It has two main operations:
#define SIZE 50
int queue[SIZE];
if (rear == SIZE - 1) {
printf("Queue Overflow\n");
return;
if (front == -1)
front = 0;
queue[++rear] = item;
int dequeue() {
printf("Queue Underflow\n");
return -1;
return queue[front++];
3. Types of Queues
In circular queues, the last position is connected back to the first position to make a circle. This avoids
the wastage of space in linear queues.
#define N 5
int cq[N];
if ((rear + 1) % N == front) {
printf("Queue Overflow\n");
return;
if (front == -1)
front = 0;
rear = (rear + 1) % N;
cq[rear] = val;
}
int dequeue() {
if (front == -1) {
printf("Queue Underflow\n");
return -1;
if (front == rear)
else
front = (front + 1) % N;
return val;
In a deque, insertion and deletion can take place from both ends.
#define SIZE 5
int deque[SIZE];
printf("Deque Overflow\n");
return;
if (front == -1) {
front = rear = 0;
} else if (front == 0) {
front = SIZE - 1;
} else {
front--;
}
deque[front] = item;
printf("Deque Overflow\n");
return;
if (front == -1) {
front = rear = 0;
rear = 0;
} else {
rear++;
deque[rear] = item;
int deleteFront() {
if (front == -1) {
printf("Deque Underflow\n");
return -1;
if (front == rear) {
front = 0;
} else {
front++;
}
return item;
int deleteRear() {
if (rear == -1) {
printf("Deque Underflow\n");
return -1;
if (front == rear) {
} else if (rear == 0) {
rear = SIZE - 1;
} else {
rear--;
return item;
A priority queue is an abstract data type where each element has a priority. Elements with higher
priority are dequeued before those with lower priority.
Example Applications: