-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.c
133 lines (114 loc) · 2.24 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 <stdio.h>
#include <stdlib.h>
#include "stack.h"
#include "vector.h"
#include "ADTDefs.h"
struct Queue
{
int* m_items;
size_t m_size; /* The size of the Queue*/
size_t m_numItems;
int m_front ;
int m_rear ;
} ;
typedef struct Queue Queue ;
Queue* QueueCreate(size_t _size)
{
Queue* temp_queue ;
if (_size == 0)
{
return NULL ;
}
temp_queue = (Queue*)malloc(sizeof(Queue)) ;
if (temp_queue == NULL)
{
return NULL ;
}
temp_queue->m_items = (int*)malloc(sizeof(int)) ;
if (temp_queue->m_items == NULL)
{
return NULL ;
}
temp_queue->m_size = _size ;
temp_queue->m_numItems = 0 ;
temp_queue->m_front = 0 ;
temp_queue->m_rear = -1 ;
return temp_queue;
}
int IsEmpty(Queue *_queue)
{
if (_queue->m_front == -1)
{
return 1;
}
return 0;
}
void QueueDestroy(Queue *_queue)
{
if (_queue != NULL)
{
free (_queue->m_items);
free (_queue);
}
return ;
}
ADTErr QueueRemove(Queue *_queue, int* _pval)
{
if ((_queue == NULL)||(_queue->m_items == NULL))
{
return ERR_NOT_INITIALIZE;
}
if ((_queue->m_rear == -1)||(_queue->m_rear < _queue->m_front))
{
printf("The array is empty, can\'t remove items.\n");
_queue->m_rear = -1;
_queue->m_front = 0;
return ERR_UNDERFLOW ;
}
if (_queue->m_numItems >= 0)
{
* _pval = _queue->m_items[_queue->m_front];
_queue->m_front = ((_queue->m_front + 1) % _queue->m_size);
_queue->m_numItems--;
}
return ERR_OK ;
}
ADTErr QueueInsert(Queue *_queue, int _val)
{
if ((_queue == NULL)||(_queue->m_items == NULL))
{
return ERR_NOT_INITIALIZE;
}
if (_queue->m_numItems == _queue->m_size)
{
printf("The Queue is full, can't enter an int.\n");
return ERR_OVERFLOW ;
}
_queue->m_rear++;
_queue->m_rear = ((_queue->m_rear)%_queue->m_size) ;
_queue->m_items[_queue->m_rear] = _val ;
_queue->m_numItems++;
return ERR_OK ;
}
int QueueIsEmpty(Queue *_queue)
{
if ((_queue == NULL)||(_queue->m_items == NULL))
{
return 0;
}
if (_queue->m_numItems == 0)
{
printf("The Queue is Empry.\n");
return 1 ;
}
return 0 ;
}
void QueuePrint(Queue *_queue)
{
int i=0;
for(i=0 ; i < _queue->m_numItems ; i++)
{
printf("The object num: %d at the Queue is: %d\n", (_queue->m_front+i), _queue->m_items[(_queue->m_front+i)%_queue->m_size]);
}
return ;
}