-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathll_queue.c
More file actions
85 lines (71 loc) · 1.68 KB
/
ll_queue.c
File metadata and controls
85 lines (71 loc) · 1.68 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
// O(1) implementation of queue linked list
#include <stdlib.h>
#include <stdbool.h>
#include "ll_queue.h"
void make_empty(ll_queue* queue) {
queue->head = NULL;
queue->rear = NULL;
}
bool is_empty(ll_queue* queue) {
return (queue->head == NULL && queue->rear == NULL) ? true : false;
}
bool has_single_element(ll_queue* queue) {
return (queue->head == queue->rear) ? true : false;
}
void enqueue(ll_queue* queue, int value) {
node* new = malloc(sizeof(node));
new->value = value;
new->next = NULL;
if (is_empty(queue)) {
queue->head = new;
queue->rear = new;
} else {
queue->rear->next = new;
queue->rear = new;
}
}
int dequeue(ll_queue* queue) {
if (is_empty(queue)) return -1;
int result = queue->head->value;
if (has_single_element(queue)) {
node* tmp = queue->head;
make_empty(queue);
free(tmp);
} else {
node* tmp = queue->head;
queue->head = queue->head->next;
free(tmp);
}
return result;
}
void free_queue(ll_queue* queue) {
if (has_single_element(queue)) {
free(queue->head);
free(queue);
return;
}
while (queue->head->next != NULL) {
node* tmp = queue->head;
queue->head = queue->head->next;
free(tmp);
}
free(queue->head);
free(queue);
}
// TODO: free linked list
// int main() {
// ll_queue* queue = malloc(sizeof(ll_queue));
// make_empty(queue);
//
// enqueue(queue, 1);
// enqueue(queue, 2);
// enqueue(queue, 3);
// enqueue(queue, 8);
//
// for (int i = 0; i < 4; i++) {
// printf("%d\n", dequeue(queue));
// }
//
//
// return 0;
// }