forked from arjuncvinod/Hello-World-in-Different-Languages
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.c
109 lines (93 loc) · 2.45 KB
/
queue.c
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
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// Structure to represent a queue
struct Queue {
int front, rear, size;
int arr[MAX_SIZE];
};
// Function to create an empty queue
struct Queue* createQueue() {
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = -1;
queue->rear = -1;
queue->size = 0;
return queue;
}
// Function to check if the queue is empty
int isEmpty(struct Queue* queue) {
return (queue->size == 0);
}
// Function to check if the queue is full
int isFull(struct Queue* queue) {
return (queue->size == MAX_SIZE);
}
// Function to add an element to the rear of the queue
void enqueue(struct Queue* queue, int item) {
if (isFull(queue)) {
printf("Queue is full. Cannot enqueue.\n");
return;
}
if (queue->front == -1) {
queue->front = 0;
}
queue->rear++;
queue->arr[queue->rear] = item;
queue->size++;
}
// Function to remove an element from the front of the queue
int dequeue(struct Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty. Cannot dequeue.\n");
return -1;
}
int item = queue->arr[queue->front];
queue->front++;
queue->size--;
return item;
}
// Function to display the elements in the queue
void display(struct Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return;
}
printf("Queue elements: ");
for (int i = queue->front; i <= queue->rear; i++) {
printf("%d ", queue->arr[i]);
}
printf("\n");
}
int main() {
struct Queue* queue = createQueue();
int choice, item;
while (1) {
printf("\n1. 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 the element to enqueue: ");
scanf("%d", &item);
enqueue(queue, item);
break;
case 2:
item = dequeue(queue);
if (item != -1) {
printf("Dequeued element: %d\n", item);
}
break;
case 3:
display(queue);
break;
case 4:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}