A queue is a first-in-first-out linear table that can only be deleted from the queue header and inserted at the end of the queue. The chain queue and single-chain table operations are similar, but there are first and last pointers, the following is the representation and implementation of chained queue:
# Include <iostream> using namespace STD; // queue chain representation and implementation of struct qnode {int data; qnode * Next ;}; struct linkqueue {qnode * front; qnode * rear;}; bool initqueue (linkqueue & Q) {q. front = Q. rear = (qnode *) malloc (sizeof (qnode); If (! Q. front) {return false;} Q. front-> next = NULL; return true;} bool destoryqueue (linkqueue & Q) {While (Q. front) {q. rear = Q. front-> next; free (Q. front); q. front = Q. rear;} return true;} // Insert the bool enqueue (linkqueue & Q, int e) element at the end of element E. {qnode * P = (qnode *) malloc (sizeof (qnode); If (! P) {return false;} p-> DATA = E; P-> next = NULL; q. rear-> next = P; q. rear = P; // The team tail pointer needs to be moved to the final return true;} bool dequeue (linkqueue & Q, Int & E) {If (Q. front = Q. rear) {return false;} qnode * P = Q. front-> next; E = p-> data; q. front-> next = p-> next; If (Q. rear = P) // You must point to the header node {q. rear = Q. front;} Free (p); Return true;} void printqueue (linkqueue & Q) {If (Q. front = Q. rear) {cout <"sorry, the queue is empty" <Endl; R Eturn;} cout <"Now print the queue:" <Endl; qnode * P = NULL; P = Q. front-> next; while (p) {cout <p-> data <Endl; P = p-> next ;}} void main () {linkqueue SCSI = {0}; If (initqueue (SCSI) {cout <"initial success! "<Endl;} int elemnum = 0; cout <" Enter the number of elements to insert: "; CIN> elemnum; int ELEM = 0; for (INT I = 0; I <elemnum; I ++) {cout <"Enter the element to insert" <I + 1 <:"; cin> ELEM; If (enqueue (SCSI, ELEM) {cout <"inserted successfully" <Endl ;;}} printqueue (SCSI ); // print the queue int delnum; dequeue (SCSI, delnum); // Delete the first element cout <"the delete num is:" <delnum <Endl; printqueue (SCSI); // print the queue destoryqueue (SCSI); // destroy the queue printqueue (SCSI); // print the queue}
The execution result is as follows: