I implemented the use of static arrays to simulate queues in the last blog, "C language implementation uses a static array implementation loop queue". Cannot dynamically expand because the size of the array has been specified. So in this blog, I'm going to switch to a dynamic array to implement. Dynamic arrays can continue to open up memory space, but will be different when the array is initialized, and the operations of other arrays are the same. Code uploaded to Https://github.com/chenyufeng1991/Queue_DynamicArray.
(1) Declaring variables
static int *queue;//declaration array
static int maxsize;//array size
static int head;//pointing head
static int tail;//pointing tail
(2) Initialization queue
Initialization queue
void initqueue (int size) {
maxSize = size;
Queue = (int *) malloc (size * sizeof (int));
Head = 0;
tail = 0;
}
(3) into the queue
Enter queue
void EnQueue (int value) {
//First determine if full
if ((tail + 1)% MaxSize = = head) {
printf ("queue full, cannot insert \ n"); c13/>}else{
//Not full
queue[tail] = value;
Tail = (tail + 1)% maxSize
}
}
(4) Out of the queue
Out Queue
int dequeue () {
int temp;
First determine if it is an empty
if (head = = tail) {
printf ("Queue is empty, column failed \ n");
} else{
temp = head;
Head = (head + 1)% MaxSize;
}
return temp;
}
(5) To determine whether the queue is empty
Determines whether the queue is empty
int IsEmpty () {
if (head = = tail) {
printf ("Queue is empty \ n");
return 1;
}
printf ("queue is not empty \ n");
return 0;
}
(6) Determine if the queue is full
Determines whether the queue is full
int isfull () {
if (tail + 1)% MaxSize = = head) {
printf (queue full \ \ n);
return 1;
}
printf ("queue is not full \ n");
return 0;
}
(7) Print queue elements
Print queue element
void PrintQueue () {
for (int i = head; i < tail; i++) {
printf ("%d", Queue[i]);
printf ("\ n");
}
(8) Test code
int main (int argc, const char * argv[]) {
initqueue (5);
EnQueue (2); EnQueue (4); EnQueue (8); EnQueue (1); EnQueue (5);
PrintQueue ();
Dequeue ();D equeue ();D equeue ();
PrintQueue ();
IsEmpty ();
Isfull ();
return 0;
}