1. Concept of queue
A queue is a special linear table that can be inserted at one end of the queue and deleted at the other end.
A queue generally has a front pointer and a rear pointer. When a queue does not store data, both the front and rear pointers point to the first.
Operations for joining the team: Move the rear back and store the data in the Unit pointed to by the rear. When the team is full, it cannot join the team. This also indicates that front always points to the front of the first element of the team.
Operations for leaving the team: Move the front back, element leaves the team, and leave the team blank.
Note: In this queue implementation mode, a unit is wasted, but this ensures that the full team and the empty team are different conditions to judge.
2. the queue is empty and the queue is full.
Empty queue: Front = rear
Full queue: the next unit of rear is front.
3. Queue Array Implementation
# Include <stdio. h> # include <malloc. h> typedef struct sq {int maxsize; int front, rear; int * quence;} QS; void init_quence (QS * s, int MS) /* initialize the queue */{S-> maxsize = MS; s-> quence = (int *) malloc (MS * sizeof (INT )); s-> front = s-> rear = 0;} void in_quence (QS * s, int Val)/* queue function */{If (S-> rear + 1) % s-> maxsize = s-> front) {printf ("quence is full. \ n "); return;} s-> rear = (S-> rear + 1) % s-> maxsize; s-> quence [S-> rear] = val;} int Out_quence (QS * s)/* team-out function */{If (S-> rear! = S-> front) {S-> front = (S-> front + 1) % s-> maxsize; return S-> quence [S-> front];} void print_quence (QS * s)/* print the elements in the queue */{int I; I = s-> front; If (S-> rear = s-> front) return; do {printf ("% d", S-> quence [(I + 1) % s-> maxsize]); I = (I + 1) % s-> maxsize;} while (I! = S-> rear);} void clear_quence (QS * s)/* clear queue */{free (S-> quence); s-> quence = 0; s-> maxsize = 0; s-> front = s-> rear = 0;} int count_quence (QS * s)/* count the number of queues */{int I, count = 0; I = s-> front; If (S-> rear = s-> front) return 0; do {count ++; I = (I + 1) % s-> maxsize;} while (I! = S-> rear); Return count;} int main () {QS s; int I; int dat [7] = {1, 2, 3, 4, 5, 6, 7}; init_quence (& S, 7); for (I = 0; I <7; I ++) {in_quence (& S, dat [I]); printf ("quence number is: % d. ", count_quence (& S); print_quence (& S); printf (" \ n ");} printf (" Out quence number is: % d. \ n ", out_quence (& S); print_quence (& S); clear_quence (& S); Return 0 ;}
Program running: