In my previous blog, the C language implementation uses a static array to implement the loop queue, which implements the operation of using a static array to simulate the queue. Because the size of the array has been specified, it cannot be expanded dynamically. So in this blog, I switch to a dynamic array to implement. Dynamic arrays can constantly open up memory space, but only when the array is initialized, the other arrays operate the same. The code is uploaded to Https://github.com/chenyufeng1991/Queue_DynamicArray.
(1) Declaring variables
static int *queue;//declaration array static int maxsize;//array size static int head;//point to head static int tail;//point to tail
(2) Initialize the queue
Initialize 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 is full, unable to insert \ n"); } else{ //Not full queue[tail] = value; Tail = (tail + 1)% MaxSize; }}
(4) Out of queue
Out of queue int DeQueue () { int temp; First determine if the null if (head = = tail) { printf ("Queue is empty, dequeue fails \ n"); } else{ temp = head; Head = (head + 1)% MaxSize; } return temp;}
(5) Determine if 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 is 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;}
C language implementation uses dynamic arrays to implement circular queues