一. 循环队列(Loop Queue)
1. 定义
#define MaxSize 10
typedef struct {
int data[MaxSize];
int front, rear;
}SqQueue;
2. 基本操作
2.1 初始化
void InitQueue(SqQueue &Q) {
Q.front = Q.rear = 0;
}
2.2 入队
bool EnQueue(SqQueue &Q, int x) {
if ((Q.rear + 1) % MaxSize == Q.front) {
return false;
}
Q.data[Q.rear] = x;
Q.rear = (Q.rear + 1) % MaxSize;
return true;
}
2.3 出队
bool DeQueue(SqQueue &Q, int &x) {
if (Q.front == Q.rear) {
return false;
}
x = Q.data[Q.front];
Q.front = (Q.front + 1) % MaxSize;
return true;
}
2.4 取队头元素
bool GetHead(SqQueue Q, int &x) {
if (Q.front == Q.rear) {
return false;
}
x = Q.data[Q.front];
return true;
}
2.5 判空
bool QueueEmpty(SqQueue Q) {
return Q.front == Q.rear;
}
二. 链队列(Linked Queue)
1. 定义
typedef struct QueueNode {
int data;
struct QueueNode *next;
}QueueNode;
typedef struct {
QueueNode *front, *rear;
}LinkQueue;
2. 基本操作
2.1 初始化
void InitQueue(LinkQueue &Q) {
Q.front = Q.rear = (QueueNode *)malloc(sizeof(QueueNode));
Q.front->next = NULL;
}
2.2 入队
void EnQueue(LinkQueue &Q, int x) {
QueueNode *p = (QueueNode *)malloc(sizeof(QueueNode));
p->data = x;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
}
2.3 出队
bool DeQueue(LinkQueue &Q, int &x) {
if (Q.front == Q.rear) {
return false;
}
QueueNode *p = Q.front->next;
x = p->data;
Q.front->next = p->next;
if (Q.rear == p) {
Q.rear = Q.front;
}
free(p);
return true;
}
2.4 取队头元素
bool GetHead(LinkQueue &Q, int &x) {
if (Q.front == Q.rear) {
return false;
}
QueueNode *p = Q.front->next;
x = p->data;
return true;
}
2.5 判空
bool QueueEmpty(LinkQueue Q) {
return Q.front == Q.rear;
}
|