-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.c
More file actions
138 lines (121 loc) · 2.41 KB
/
queue.c
File metadata and controls
138 lines (121 loc) · 2.41 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
/* use single-linked list to implement queue */
#include <stdio.h>
#include <stdlib.h>
typedef struct node *position;
typedef int ElementTP;
// point to the head node of the list
typedef struct HeadNode *QUEUE;
struct node {
ElementTP element;
position next;
};
/*
* CAUTIOUS: "HeadNode" is different from "node",
* it's another struct
* end: points to the last value in the queue
*/
struct HeadNode {
ElementTP element;
position next;
position end;
};
/*
* Operations
*/
QUEUE init_queue(void);
void delete_queue(QUEUE);
void enqueue(QUEUE, ElementTP);
ElementTP dequeue(QUEUE);
int is_null(QUEUE);
/*
* Test
*/
void main(void)
{
ElementTP a;
int i;
QUEUE qu;
qu = init_queue();
enqueue(qu, 1);
enqueue(qu, 2);
enqueue(qu, 8);
printf("Queue is null? %d\n", is_null(qu));
for (i=0; i<3; i++) {
a = dequeue(qu);
printf("dequeue: %d\n", a);
}
printf("Queue is null? %d\n", is_null(qu));
delete_queue(qu);
}
/*
* initiate the queue
* malloc the head node.
* Head node doesn't store valid data
* head->next is the first node in the queue.
*/
QUEUE init_queue(void)
{
QUEUE hnp;
hnp = (QUEUE) malloc(sizeof(struct HeadNode));
hnp->next = NULL; // qu->next is the first node
hnp->end = NULL;
return hnp;
}
/*
* dequeue all elements
* and then delete head node
*/
void delete_queue(QUEUE qu)
{
while(!is_null(qu)) {
dequeue(qu);
}
free(qu);
}
/*
* enqueue a value to the end of the queue
*/
void enqueue(QUEUE q, ElementTP value)
{
position np, oldEnd;
// oldEnd = qu->end;
np = (position) malloc(sizeof(struct node));
np->element = value;
np->next = NULL;
/* if queue is empyt, then oldEnd is NULL */
// if (oldEnd) {
if (q->end) {
(q->end)->next = np;
//oldEnd->next = np;
} else {
q->next = np;
}
q->end = np;
}
/*
* dequeue the first value
*/
ElementTP dequeue(QUEUE qu)
{
ElementTP element;
position first, newFirst;
if (is_null(qu)) {
printf("dequeue() on an empty queue");
exit(1);
}
else {
first = qu->next;
element = first->element;
newFirst = first->next;
qu->next = newFirst;
free(first);
return element;
}
}
/*
* check: queue is empty?
*/
int is_null(QUEUE qu)
{
return (qu->next == NULL);
}