队列的初始化、判断队空、入队、出队
#include <iostream>
#define MaxSize 50
typedef struct{
int data[MaxSize];
int front, rear;
}SqQueue;
//队列初始化
void InitSqQueue(SqQueue& Q) {
Q.rear = Q.front = 0;//初始化队首、队尾指针
}
//判断队空
bool isEmpty(SqQueue Q) {
if (Q.rear == Q.front)//队空条件
return true;
else
return false;
}
//入队
bool EnQueue(SqQueue& Q,int e) {
if ((Q.rear + 1) % MaxSize == Q.front)//队满则报错
return false;
Q.data[Q.rear] = e;
Q.rear = (Q.rear + 1)%MaxSize;//队尾指针加一取模
return true;
}
//出队
bool DeQueue(SqQueue& Q, int& e) {
if (Q.rear == Q.front)//队空则报错
return false;
e = Q.data[Q.front];
Q.front = (Q.front + 1) % MaxSize;//队头指针加一取模
return true;
}
链式队列的初始化、判断队空、入队、出队
typedef struct LinkNode{//链式队列结点
int data;
struct LinkNode *next;
}LinkNode;
typedef struct {//链式队列
LinkNode* front, * rear;//队列的队头和队尾指针
}LinkQueue;
//初始化链式队列(带头结点)
void InitLinkQueue(LinkQueue& Q) {
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.front = NULL;
}
//判断队空
bool IsEmpty(LinkQueue Q) {
if (Q.front == Q.rear)//不带头结点,Q.front==NULL
return true;
else
return false;
}
//入队(带头结点)
bool EnLinkQueue(LinkQueue& Q, int e) {
LinkNode *s = (LinkNode*)malloc(sizeof(LinkNode));
s->data = e;
s->next = NULL;//创建新结点插入到链尾
Q.rear->next = s;
Q.rear = s;
return true;
}
//入队(不带头结点)
bool EnLinkQueue(LinkQueue& Q, int e) {
LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
s->data = e;
s->next = NULL;//创建新结点插入到链尾
if (Q.front == NULL) {
Q.front = s;
Q.rear = s;
}
else {
Q.rear->next = s;
Q.rear = s;
}
return true;
}
//出队
bool DeLinkQueue(LinkQueue& Q, int& e) {
if (Q.front == Q.rear)//空队
return false;
LinkNode *q = Q.front->next;
e = q->data; //变量e返回队头元素
Q.front->next = q->next;//修改头结点的next指针
if (Q.rear = q) //此次是最后一个结点出队
Q.rear = Q.front; //修改rear指针
free(q);
return true;
}
//出队
bool DeLinkQueue(LinkQueue& Q, int& e) {
if (Q.front == Q.rear)//空队
return false;
LinkNode* q = Q.front;//q指向此次出队的结点
e = q->data; //变量e返回队头元素
Q.front->next = q->next;//修改rear指针
if (Q.rear = q) { //此次是最后一个结点出队
Q.front = NULL;
Q.rear = NULL;
}
free(q);
return true;
}