-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.c
More file actions
86 lines (74 loc) · 1.61 KB
/
Copy pathqueue.c
File metadata and controls
86 lines (74 loc) · 1.61 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
#include <stdio.h>
#define MAX_SIZE 100
typedef struct {
int items[MAX_SIZE];
int front, rear;
} Queue;
// Initialize
void initQueue(Queue *q) {
q->front = -1;
q->rear = -1;
}
// Check if empty
int isEmpty(Queue *q) {
return q->front == -1;
}
// Check if full
int isFull(Queue *q) {
return q->rear == MAX_SIZE - 1;
}
// Enqueue (insert at rear)
void enqueue(Queue *q, int value) {
if (isFull(q)) {
printf("Queue is full!\n");
return;
}
if (isEmpty(q))
q->front = 0;
q->items[++(q->rear)] = value;
}
// Dequeue (remove from front)
int dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return -1;
}
int value = q->items[q->front];
if (q->front == q->rear)
initQueue(q); // queue becomes empty
else
q->front++;
return value;
}
// Peek (front element without removing)
int peekQueue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return -1;
}
return q->items[q->front];
}
// Display
void displayQueue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return;
}
printf("Queue (front -> rear): ");
for (int i = q->front; i <= q->rear; i++)
printf("%d ", q->items[i]);
printf("\n");
}
// Main test
int main() {
Queue q;
initQueue(&q);
enqueue(&q, 10);
enqueue(&q, 20);
enqueue(&q, 30);
displayQueue(&q); // 10 20 30
printf("Dequeued: %d\n", dequeue(&q)); // 10
printf("Front element: %d\n", peekQueue(&q)); // 20
displayQueue(&q); // 20 30
return 0;
}