Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()
✅ Step-by-Step Explanation
🔹 Queue Structure
queue[MAX]
: Array to store elementsfront
: Points to first element (initialized to -1)rear
: Points to last element (initialized to -1)
🔹 Insert Operation
void insert(int val) {
if(rear == MAX - 1) {
printf("Queue Overflow! Cannot insert %d\n", val);
} else {
if(front == -1) front = 0;
rear++;
queue[rear] = val;
}
}
- Overflow check: If rear == MAX-1, queue is full
- First insertion: Sets front to 0 when inserting first element
- Normal insertion: Increments rear and adds element
🔹 Delete Operation
void delete() {
if(front == -1 || front > rear) {
printf("Queue Underflow! No elements to delete.\n");
} else {
printf("%d deleted from the queue.\n", queue[front]);
front++;
}
}
- Underflow check: If front == -1 or front > rear, queue is empty
- Normal deletion: Removes element at front and increments front pointer
🔹 Display Operation
void display() {
if(front == -1 || front > rear) {
printf("Queue is empty.\n");
} else {
printf("Queue elements: ");
for(int i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
printf("\n");
}
}
- Displays all elements from front to rear
- Shows empty message if queue is empty
🖨️ Example Run (Sample Output)
10 inserted into the queue. 20 inserted into the queue. 30 inserted into the queue. Queue elements: 10 20 30 10 deleted from the queue. Queue elements: 20 30 40 inserted into the queue. 50 inserted into the queue. Queue Overflow! Cannot insert 60 Queue elements: 20 30 40 50 20 deleted from the queue. 30 deleted from the queue. 40 deleted from the queue. 50 deleted from the queue. Queue Underflow! No elements to delete. Queue is empty.
📌 Key Concepts Covered
FIFO Principle
First-In-First-Out behavior of queues
Array Implementation
Using array with front and rear pointers
Overflow/Underflow
Handling queue full and empty conditions
Basic Operations
Insert (enqueue), Delete (dequeue), and Display
Pointer Management
Proper handling of front and rear pointers
No comments:
Post a Comment