forked from callmefarhan/DATA-STRUCTURE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EXP2b.txt
97 lines (86 loc) · 2.47 KB
/
EXP2b.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
// Queue structure
static int queue[MAX];
int front = -1;
int rear = -1;
// Function to insert an element into the queue
void insert(int x) {
if ((rear + 1) % MAX == front) { // Check for full condition
printf("\nQueue Full\n");
return;
}
// If queue is empty, initialize front and rear
if (front == -1) {
front = 0;
}
rear = (rear + 1) % MAX; // Circular increment
queue[rear] = x;
printf("\n%d inserted into the queue\n", x);
}
// Function to remove an element from the queue (renamed from remove to dequeue)
int dequeue() {
if (front == -1) { // Check for empty condition
printf("\nQueue Empty\n");
return -1; // Return an invalid value
}
int val = queue[front];
if (front == rear) {
// Queue is now empty after this removal
front = rear = -1;
} else {
front = (front + 1) % MAX; // Circular increment
}
return val;
}
// Function to view the elements in the queue
void view() {
if (front == -1) {
printf("\nQueue Empty\n");
} else {
printf("\nFront --> ");
int i = front;
while (1) {
printf("%4d", queue[i]);
if (i == rear) break; // Stop when we reach the rear
i = (i + 1) % MAX; // Circular increment
}
printf(" <-- Rear\n");
}
}
// Main function to drive the queue operations
int main() {
int choice = 0, val;
while (choice != 4) {
printf("\nQUEUE OPERATIONS\n");
printf("1. INSERT\n");
printf("2. DELETE\n");
printf("3. VIEW\n");
printf("4. QUIT\n");
printf("Enter Choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter element to be inserted: ");
scanf("%d", &val);
insert(val);
break;
case 2:
val = dequeue(); // Changed from remove() to dequeue()
if (val != -1) {
printf("Element deleted: %d\n", val);
}
break;
case 3:
view();
break;
case 4:
printf("Exiting...\n");
exit(0);
default:
printf("\nInvalid Choice\n");
}
}
return 0;
}