We can know some things from the book.
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef int QueueElementType;
// Generally, the operation is to package the head pointer of the queue and the tail pointer of the queue
// in one structure
// Defintion of queue structure
typedef struct Node{
QueueElementType data; // data region
struct Node* next; // pointer domain
}LinkQueueNode;
typedef struct{
LinkQueueNode * front; //
LinkQueueNode * rear;
}LinkQueue;
// we need to have mastered the most basic operation such as initialize、incoming queue、 out of queue and so on
// Initialize the queue
void InitQueue(LinkQueue * Q)
{ // Initialize the queue Q to an empty queue
Q->front = (LinkQueueNode * )malloc(sizeof(LinkQueueNode));
if(Q->front!=NULL)
{
Q->rear = Q->front;
Q->front->next = NULL;
}
else {
// overflow
}
}
// incoming queue
void EnterQueue(LinkQueue * Q,QueueElementType x)
{ // Insert the element x into the queue Q
LinkQueueNode * NewNode;
NewNode =(LinkQueueNode * )malloc(sizeof(LinkQueueNode));
if(NewNode!=NULL)
{
NewNode->data = x;
NewNode->next = NULL;
Q->rear->next = NewNode;
Q->rear = NewNode;
}
else{
cout << "failure"<<endl;
}
}
// out of queue ,similar to deleting an element from the queue
void DeleteQueue(LinkQueue * Q,QueueElementType * x)
{ // Out of an element from the queue Q and reserve the element in the definition constant x.
LinkQueueNode * p;
if(Q->front == Q->rear)
{
}
p = Q->front->next; // the head element of the queue
Q->front->next = p->next; // similar to deleting the head element of the queue
if(Q->rear == p) // if the queue has only one element,p becomes an empty queue after it leaves the queue
{
Q->rear = Q->front;
}
*x = p->data; // reserve the "p->data" in x
free(p); // release memory space
}
int main()
{
LinkQueue Q;
InitQueue(&Q);
cout << " input a number is 2"<<endl;
cout << " execute Enter..." <<endl;
EnterQueue(&Q,2);
int x;
cout << " execute Delete..." <<endl;
DeleteQueue(&Q,&x);
cout << " Save the deleted elements to x,and x's value: " << x <<endl;
}