-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathqueue.h
More file actions
158 lines (136 loc) · 2.58 KB
/
queue.h
File metadata and controls
158 lines (136 loc) · 2.58 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
// Define the Node struct for the queue
typedef struct Node
{
struct PCB data;
struct Node *next;
} Node;
// Define the Queue struct
typedef struct Queue
{
Node *front;
Node *rear;
} Queue;
// Initialize the queue
void init_queue(Queue *q)
{
q->front = NULL;
q->rear = NULL;
}
// Check if the queue is empty
int is_empty(Queue *q)
{
return (q->front == NULL);
}
// Add an element to the queue
void enqueue(Queue *q, struct PCB data)
{
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
if (is_empty(q))
{
q->front = new_node;
q->rear = new_node;
}
else
{
q->rear->next = new_node;
q->rear = new_node;
}
}
// Remove an element from the queue
struct PCB dequeue(Queue *q)
{
if (is_empty(q))
{
printf("Queue is empty.\n");
struct PCB empty_pcb = {0};
return empty_pcb;
}
struct PCB data = q->front->data;
Node *temp = q->front;
if (q->front == q->rear)
{
q->front = NULL;
q->rear = NULL;
}
else
{
q->front = q->front->next;
}
free(temp);
return data;
}
// Get the front element of the queue
struct PCB front(Queue *q)
{
if (is_empty(q))
{
printf("Queue is empty.\n");
struct PCB empty_pcb = {0};
return empty_pcb;
}
return q->front->data;
}
// Get the size of the queue
int queue_size(Queue *q)
{
int count = 0;
Node *current = q->front;
while (current != NULL)
{
count++;
current = current->next;
}
return count;
}
// Delete the queue
void delete_queue(Queue *q)
{
Node *current = q->front;
while (current != NULL)
{
Node *temp = current;
current = current->next;
free(temp);
}
q->front = NULL;
q->rear = NULL;
}
// Find the required id
void dequeueid(struct Queue *q, int id)
{
// Check if the queue is empty
if (q->front == NULL)
{
return;
}
// Traverse the queue to find the node with the given ID
struct Node *prev = NULL;
struct Node *curr = q->front;
while (curr != NULL && curr->data.fileInfo.id != id)
{
prev = curr;
curr = curr->next;
}
// If the ID is not found, return NULL
if (curr == NULL)
{
return;
}
// Remove the node from the queue
if (prev == NULL)
{
q->front = curr->next;
}
else
{
prev->next = curr->next;
}
if (curr == q->rear)
{
q->rear = prev;
}
// free the node
free(curr);
}