-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.c
executable file
·121 lines (110 loc) · 2.48 KB
/
queue.c
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
#include "queue.h"
/* createQueue
* input: none
* output: a pointer to a queue (this is malloc-ed so must be freed eventually!)
*
* Creates a new empty queue and returns a pointer to it.
*/
Queue *createQueue( )
{
Queue *pq = (Queue *)malloc( sizeof(Queue) );
if( pq!=NULL )
{
pq->qFront = NULL;
pq->qRear = NULL;
}
return pq;
}
/* freeQueue
* input: a pointer to a Queue
* output: none
*
* frees the given Queue pointer. Also, you should remember to free the elements in the linked list!
*/
void freeQueue( Queue *pq )
{
free(pq);
}
/* getNext
* input: a pointer to a Queue
* output: a pointer to process
*
* Returns the process stored at the front of the Queue. It does not remove the element from the queue.
*/
queueType getNext( Queue *pq )
{
if( isEmpty( pq ) )
{
/* no element to return */
fprintf( stderr, "getNext: Queue is empty (returning NULL).\n" );
return NULL;
}
return pq->qFront->qt;
}
/* dequeue
* input: a pointer to a Queue
* output: a queueType
*
* Dequeues and returns the queueType stored at the front of the Queue. It does not free the dequeue-ed element.
*/
queueType dequeue( Queue *pq )
{
LLNode *temp;
queueType qt;
if( isEmpty( pq ) )
{
/* no element to return */
fprintf( stderr, "dequeue: Queue is empty (returning NULL).\n" );
return NULL;
}
temp = pq->qFront;
pq->qFront = pq->qFront->pNext;
if( pq->qFront==NULL ){
pq->qRear=NULL;
}
qt = temp->qt;
free(temp);
return qt;
}
/* enqueue
* input: a pointer to a Queue, a queueType
* output: none
*
* Inserts the process on the rear of the given Queue.
*/
void enqueue( Queue *pq, queueType qt )
{
LLNode *node = (LLNode*)malloc(sizeof(LLNode));
if(node==NULL){
fprintf( stderr, "enqueue: Failed to allocate memory");
exit(-1);
}
node->pNext=NULL;
node->qt = qt;
if( isEmpty(pq) ){
pq->qFront = node;
pq->qRear = node;
return;
}
pq->qRear->pNext = node;
pq->qRear = node;
}
/* isEmpty
* input: a pointer to a Queue
* output: a boolean
*
* returns TRUE if the Queue is empty and FALSE otherwise
*/
bool isEmpty( Queue *pq )
{
if( pq->qFront==NULL && pq->qRear==NULL )
{
return true;
}
else if( pq->qFront==NULL || pq->qRear==NULL )
{
fprintf( stderr, "isEmpty: Queue had inconsistent values for front and rear.\n" );
exit(-1);
}
return false;
}