【队列】
顺序队列
如果不采用循环队列的方式,很多空间会被浪费掉,效率低,因此使用循环队列。
循环队列:
- 头指针:第一个元素
- 尾指针:最后一个元素的下一个元素
- 判空:front == rear
- 判满:front == (rear + 1) % MaxSize
- 入队尾后移:rear = (rear + 1) % MaxSize
- 出队头后移:front = (front + 1) % MaxSize
1.实现
typedef struct QNode *Queue;
struct QNode {
ElementType Data[MaxSize];
int Front,Rear; // 头尾指针,头指向队列首元素,尾指向队列最后一个元素的下一位置
};
2.建立空队列
Queun CreateQueue()
{
Queue Q = (Queue)malloc(sizeof(struct QNode));
Q -> Front = Q -> Rear = 0;
return Q;
}
3.入队
void AddQ(Queue Q,ElementType e)
{
if(IsFull(Q))
return;
else {
Q -> Data[Q -> Rear] = e;
Q -> Rear = (Q -> Rear + 1) % Maxsize;
}
}
4.出队
ElementType DeleteQ(Queue Q)
{
if(IsEmpty(Q))
return;
else {
Q -> Front = (Q -> Front + 1) % MaxSize;
return Q -> Data[Q -> Front - 1];
}
}
5.判空
int IsEmpty(Queue Q)
{
return(Q -> Front == Q -> Rear);
}
6.判满
int IsFull(Queue Q)
{
return(Q -> Front == (Q -> Rear + 1) % MaxSize);
}
链式队列
- 头指针:第一个元素
- 尾指针:最后一个元素
- 判空:front =NULL rear == NULL
1.实现
typedef struct Node *QNode;
struct Node {
ElementType Data;
QNode Next;
}
typedef struct Que *Queue;
struct Que {
QNode Front,Rear;
}
2.通过给定元素建立一个队列
// 通过给定的元素建立一个队列
Queue CreateQueue(ElementType e)
{
Queue Q;
QNode QN;
Q = (Queue)malloc(sizeof(struct Que));
QN = (QNode)malloc(sizeof(struct Node));
Q -> Front = Q -> Rear = QN;
QN -> Data = e;
QN -> Next = NULL;
return Q;
}
3.入队
void AddQ(Queue Q,ElementType e)
{
QNode QN;
QN = (QNode)malloc(sizeof(struct Node));
QN -> Data = e;
QN -> Next = NULL;
// 注意需要判空,因为当对空队列做入队操作时,需要将头指针指向该元素
if(IsEmpty(Q)) {
Q -> Front = Q -> Rear = QN;
}
else {
Q -> Rear -> Next = QN;
Q -> Rear = QN;
}
}
4.出队
ElementType DeleteQ(Queue Q)
{
ElementType data; // 放置要出队的元素的值
QNode QN; // 放置要出队的元素结点
if(IsEmpty(Q))
return;
if(Q -> Front == Q -> Rear && Q -> Front != NULL) { // 队列中只有一个元素
data = Q -> Front -> Data;
QN = Q -> Front;
free(QN);
Q -> Front = Q -> Rear = NULL; // 将队列设置为空
}
else {
data = Q -> Front -> Data;
QN = Q -> Front;
free(QN);
Q -> Front = Q -> Front -> Next;
}
return data;
}
5.判空
int IsEmpty(Queue Q)
{
return(Q -> Front == Q -> Rear && Q -> Front == NULL);
}