forked from HamdaAnees/DataStructure-Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqueue.c
132 lines (112 loc) · 2.8 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
121
122
123
124
125
126
127
128
129
130
131
132
#include "queue.h"
#include "fatal.h"
#include <stdlib.h>
#define MinQueueSize ( 5 )
struct QueueRecord
{
int Capacity;
int Front;
int Rear;
int Size;
ElementType *Array; // modify array to store stuructue in queue
};
/* START: fig3_58.txt */
int
IsEmpty( Queue Q )
{
return Q->Size == 0;
}
/* END */
int
IsFull( Queue Q )
{
return Q->Size == Q->Capacity;
}
Queue
CreateQueue( int MaxElements )
{
Queue Q;
/* 1*/ if( MaxElements < MinQueueSize )
/* 2*/ Error( "Queue size is too small" );
/* 3*/ Q = malloc( sizeof( struct QueueRecord ) );
/* 4*/ if( Q == NULL )
/* 5*/ FatalError( "Out of space!!!" );
/* 6*/ Q->Array = malloc( sizeof( ElementType ) * MaxElements );
/* 7*/ if( Q->Array == NULL )
/* 8*/ FatalError( "Out of space!!!" );
/* 9*/ Q->Capacity = MaxElements;
/*10*/ MakeEmpty( Q );
/*11*/ return Q;
}
/* START: fig3_59.txt */
void
MakeEmpty( Queue Q )
{
Q->Size = 0;
Q->Front = 1;
Q->Rear = 0;
}
/* END */
void
DisposeQueue( Queue Q )
{
if( Q != NULL )
{
free( Q->Array );
free( Q );
}
}
/* START: fig3_60.txt */
static int
Succ( int Value, Queue Q )
{
if( ++Value == Q->Capacity )
Value = 0;
return Value;
}
void
Enqueue( ElementType X, Queue Q )
{
if( IsFull( Q ) )
Error( "Full queue" );
else
{
Q->Size++;
Q->Rear = Succ( Q->Rear, Q );
Q->Array[ Q->Rear ] = X;
}
}
/* END */
ElementType
Front( Queue Q )
{
if( !IsEmpty( Q ) )
return Q->Array[ Q->Front ];
Error( "Empty queue" );
return 0; /* Return value used to avoid warning */
}
void
Dequeue( Queue Q )
{
if( IsEmpty( Q ) )
Error( "Empty queue" );
else
{
Q->Size--;
Q->Front = Succ( Q->Front, Q );
}
}
ElementType
FrontAndDequeue( Queue Q )
{
ElementType X = 0;
if( IsEmpty( Q ) )
Error( "Empty queue" );
else
{
Q->Size--;
X = Q->Array[ Q->Front ];
Q->Front = Succ( Q->Front, Q );
}
return X;
}