1. Definition
1. Queue is a first-in, first-out linear table, and its operation can only be performed on both ends of the table.
2. Classification: chain queue-chain representation; circular queue-sequential representation
Second, the chain queue
Node structure:
typedef struct QNode{
int data;
struct QNode *next;
}QNode,*QPtr;
Chain queue structure
typedef struct {
QPtr *front; //队首指针
QPtr *rear; //队尾指针
}LinkQueue;
Create empty queue
Status InitQueue(LinkQueue Q)
{
Q.front=Q.rear=(QNode*)malloc(sizeof(QNode));
if(!Q.front)exit(0); //存储分配失败
Q.front->next=NULL;
}
Enqueue operation
EnQueue(LinkQueue Q,int e)
{
QPtr p=(QNode*)malloc(sizeof(QNode));
if(!p)exit(0);//储存分配失败
p->next=NULL;
p->data=e;
Q.rear->next=p;
Q.rear=p;
}
Dequeue operation
DeQueue(LinkQueue Q,int e)
{
QPtr p=(QNode*)malloc(sizeof(QNode));
if(!p)exit(0);//储存分配失败
if(Q.front==Q.rear)return ERROR;//队列为空,无法完成出队操作
p=Q.front->next;
e=p->data;
Q.front->next=p->next;
if(Q.rear==p)Q>front=Q.rear;
free(p);
}
Three, sequential queue-array representation
Enqueue operation
EnQueue(Q[MAX],int x)
{
if(rear+1>=MAX)cout<<"队满"<<endl;
else
{
Q[rear]=x;
rear++;
}
}
Dequeue operation
DeQueue(Q[MAX],int e)
{
if(front==rear)cout<<"队空"<<endl;
else
{
e=Q[front];
front++;
return e;
}
}
Four, circular queue
Note: The
conditions for full team are:
(rear+1)%MAX==front
The team empty conditions are:
rear==front