Data Structure: queue and cyclic queue; Data Structure: cyclic queue
Note: Yan Weimin's "data structure" (C language version) takes notes and records them for later viewing.
# Include <stdio. h> # include <stdlib. h ># define OK 1; # define ERROR-1; typedef int QElemType; typedef int Status; // defines the queue node typedef struct QNode {QElemType data; struct QNode * next ;} QNode, * QueuePtr; // queue typedef struct {QueuePtr front; // queue head pointer QueuePtr rear; // team end pointer} LinkQueue; // initialize queue Status InitQueue (LinkQueue * q) {q-> front = q-> rear = (QueuePtr) malloc (sizeof (QNode); if (! Q-> front) return ERROR; q-> front-> next = NULL; return OK;} // destroy the queue Status DestroyQueue (LinkQueue * q) {while (q-> front) {q-> rear = q-> front-> next; free (q-> front ); q-> front = q-> rear;} return OK;} // Insert the element Status EnQueue (LinkQueue * q, QElemType e) {QueuePtr p = (QueuePtr) malloc (sizeof (QNode); if (! P) return ERROR; p-> data = e; p-> next = NULL; q-> rear-> next = p; // point to p q-> rear = p at the end of the queue; // p is recorded as the tail pointer return OK;} // output queue Status DeQueue (LinkQueue * q, QElemType * e) {if (q-> front = q-> rear) return ERROR; QueuePtr p = q-> front-> next; // point to the first element in the queue header * e = p-> data; q-> front-> next = p-> next; if (q-> rear = p) q-> rear = q-> front; free (p); return OK ;}
During initialization, both front and rear are equal to 0. The number of queue elements is 0.
In this case, the number of queue elements is rear-front = 4. If the queue changes to the following format, rear <front
The reason why the queue is empty is to distinguish whether the queue is "empty" or "full". When the next position of the queue's tail pointer is the header pointer, the queue is full.
# Include <stdio. h> # include <stdlib. h> # define OK 1 # define ERROR-1 # define MAXQSIZE 100 // maximum queue length typedef int QElemType; typedef int Status; // cyclic queue typedef struct {QElemType * base; int front; int rear;} SqQueue; // initialize the cyclic queue Status InitQueue (SqQueue * q) {q-> base = (QElemType *) malloc (MAXQSIZE * sizeof (QElemType); if (! Q) return ERROR; q-> front = q-> rear = 0; return OK;} // get the queue length int QueueLength (SqQueue * q) {return (q-> rear-q-> front + MAXQSIZE) % MAXQSIZE;} // queue Status EnQueue (SqQueue * q, QElemType e) {if (q-> rear + 1) % MAXQSIZE = q-> front) {return ERROR;} q-> base [q-> rear] = e; q-> rear = (q-> rear + 1) % MAXQSIZE; return OK;} // departure Status DeQueue (SqQueue * q, QElemType * e) {if (q-> front = q-> rear) return ERROR; * e = q-> base [q-> front]; q-> front = (q-> front + 1) % MAXQSIZE; return OK ;}