-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue_array.c
More file actions
112 lines (94 loc) · 2.45 KB
/
Copy pathqueue_array.c
File metadata and controls
112 lines (94 loc) · 2.45 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5 // maximum size of the queue
struct Queue {
int items[SIZE];
int front, rear;
};
// Function to create an empty queue
struct Queue* createQueue() {
struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = -1;
q->rear = -1;
return q;
}
// Function to check if queue is full
int isFull(struct Queue* q) {
if (q->rear == SIZE - 1)
return 1;
return 0;
}
// Function to check if queue is empty
int isEmpty(struct Queue* q) {
if (q->front == -1 || q->front > q->rear)
return 1;
return 0;
}
// Function to add an element to the queue
void enQueue(struct Queue* q, int value) {
if (isFull(q)) {
printf("Queue is full! Cannot enqueue.\n");
return;
}
if (q->front == -1) // if queue is empty
q->front = 0;
q->rear++;
q->items[q->rear] = value;
printf("Enqueued: %d\n", value);
}
// Function to remove an element from the queue
void deQueue(struct Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty! Cannot dequeue.\n");
return;
}
printf("Dequeued: %d\n", q->items[q->front]);
q->front++;
// Reset the queue if it becomes empty
if (q->front > q->rear)
q->front = q->rear = -1;
}
// Function to display the queue
void display(struct Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return;
}
printf("Queue elements: ");
for (int i = q->front; i <= q->rear; i++) {
printf("%d ", q->items[i]);
}
printf("\n");
}
// Driver code
int main() {
struct Queue* q = createQueue();
int choice, value;
while (1) {
printf("\n--- Queue Menu (Array Implementation) ---\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to enqueue: ");
scanf("%d", &value);
enQueue(q, value);
break;
case 2:
deQueue(q);
break;
case 3:
display(q);
break;
case 4:
exit(0);
default:
printf("Invalid choice! Try again.\n");
}
}
return 0;
}