-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.c
More file actions
70 lines (64 loc) · 1.12 KB
/
queue.c
File metadata and controls
70 lines (64 loc) · 1.12 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
// File: queue.c
// Include this file *after* including <stdlib.h>
typedef struct node
{
struct node * next;
int val;
}
node;
typedef struct
{
node * head;
node * tail;
int len;
}
queue;
queue * q_new()
{
queue * data = malloc(sizeof(queue));
data->head = NULL;
data->tail = NULL;
data->len = 0;
return data;
}
void q_free(queue * data)
{
if (data == NULL) return;
while (data->head != NULL)
{
data->tail = data->head;
data->head = data->head->next;
free(data->tail);
}
free(data);
}
void q_push(queue * data, int init_val)
{
if (data->tail == NULL)
{
data->tail = malloc(sizeof(node));
data->head = data->tail;
}
else
{
data->tail->next = malloc(sizeof(node));
data->tail = data->tail->next;
}
data->tail->val = init_val;
data->tail->next = NULL;
data->len += 1;
}
void q_pop(queue * data)
{
if (data->head == NULL) return;
node * temp = data->head;
data->head = data->head->next;
free(temp);
data->len -= 1;
if (data->head == NULL) data->tail = NULL;
}
int q_front(queue * data)
{
if (data->head == NULL) return 0;
else return data->head->val;
}