# 一、队列的顺序表示

## （三）解决办法

``````//入队
Q.base[Q.rear] = x;
Q.rear = (Q.rear + 1) % MAXSIZE;
//队满判定条件
(Q.rear + 1) % MAXSIZE == Q.front(少用一存储单元)
``````

``````//出队
x = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXSIZE;
//队空判定条件
Q.rear == Q.front;
``````

## （四）循环队列

### 1、循环队列初始化

``````#define MAXQSIZE 100
typedef struct
{

QElemType* base;
int front;
int rear;
}SqQueue;

Status InitQueue(SqQueue& Q)
{

Q.base = new QElemType[MASQSIZE];//开辟空间
if (!Q.base) exit(OVERFLOW);//存储分配失败
Q.front = Q.rear = 0;
return OK;
}
``````

### 2、循环队列入队

``````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;
}
``````

### 3、循环队列出队

``````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;
}
``````

# 二、链队

## （一）链队的表示

### 1、队列的链式存储结构

``````typedef struct QNode
{

QElemType data;
struct QNode* next;
}QNode,*QueuePtr;
typedef struct
{

QueuePtr front;//队头指针
QueuePtr rear;//队尾指针

``````

## （二）链队的基本操作

### 1、链队的初始化

``````Status InitQueue(LinkQueue& Q)
{

Q.front = Q.rear = new QNode;
if(!Q.front) exit(OVERFLOW);
Q.front->next = NULL;
return OK;
}
``````

### 2、链队的入队

``````Status EnQueue(LinkQueue& Q, QElemType e)
{

p = new QNode;
if (!p) exit(OVERFLOW);//存储分配失败
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return OK;
}
``````

### 3、链队的出队

``````Status DeQueue(LinkQueue& Q, QElemType& e)
{

if (Q.front == Q.rear)
return ERROR;//队列为空
p = Q.front->next;//p指向队头元素
e = p->data;//e保存队头元素的值
Q.front->next = p->next;//修改头指针
if (Q.rear == p)
Q.rear = Q.front;//如果最后一个元素被删，则队尾指针指向头结点
delete p;//释放原队头元素的空间
return OK;

}
``````