-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue_Arrays.c
106 lines (91 loc) · 2.06 KB
/
Queue_Arrays.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
#include <stdio.h>
#include <stdlib.h>
int front = -1; int rear = -1, size;
int *initArray(int size){
int *array = calloc(size, sizeof(int));
return array;
}
void PrintQueue(int *queue, int size)
{
if (front == -1 && rear == -1)
{
printf("Queue is empty.\n");
return;
}
int i;
for (i = front; i != rear; i = ( i + 1 ) % size)
{
printf("%d\t", queue[i]);
}
printf("%d\n", queue[i]);
}
int Enqueue(int *array, int size, int data)
{
if ((rear + 1) % size == front)
{
printf("Queue is full. Cannot enqueue.\n");
return -1;
}
if (front == -1 && rear == -1)
{
front = rear = 0;
}
else
{
rear = (rear + 1) % size;
}
array[rear] = data;
return 0;
}
int Dequeue(int *array, int size)
{
if (front == -1 && rear == -1)
{
printf("Queue is empty. Cannot dequeue.\n");
return -1;
}
printf("Dequeued element: %d\n", array[front]);
if (front == rear)
{
front = rear = -1;
}
else
{
front = (front + 1) % size;
}
}
int main()
{
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int *queue = initArray(size);
do
{
printf("\n1. Display\n2. Enqueue\n3. Dequeue\n0. Exit\n");
printf("Your choice: ");
int choice;
scanf("%d", &choice);
switch (choice)
{
case 1:
PrintQueue(queue, size);
break;
case 2:
printf("Enter the element to enqueue: ");
int data;
scanf("%d", &data);
Enqueue(queue, size, data);
break;
case 3:
Dequeue(queue, size);
break;
case 0:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
} while (1);
free(queue);
}