1. 静态循环队列
代码:
# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
# include <stdbool.h>
typedef struct Queue {
int *pBase;
int front;
int rear;
} QUEUE;
void init(QUEUE *);
bool enter_queue(QUEUE *, int);
void traverse_queue(QUEUE *);
bool full_queue(QUEUE *);
bool dequeue(QUEUE *, int *);
bool empty_queue(QUEUE *);
int main() {
QUEUE Q;
int val;
init(&Q);
traverse_queue(&Q);
enter_queue(&Q, 1);
enter_queue(&Q, 2);
enter_queue(&Q, 3);
enter_queue(&Q, 4);
enter_queue(&Q, 5);
if (!enter_queue(&Q, 6))
printf("满了\n");
traverse_queue(&Q);
if (dequeue(&Q, &val)) {
printf("出队成功,出队元素为%d\n", val);
}
traverse_queue(&Q);
return 0;
}
void init(QUEUE *pQ) {
pQ->pBase = (int *)malloc(sizeof(int) * 6);
if (pQ->pBase == NULL) {
printf("分配失败!\n");
exit(-1);
}
pQ->front = 0;
pQ->rear = 0;
return;
}
bool full_queue(QUEUE *pQ) {
if ((pQ->rear + 1) % 6 == pQ->front) {
return true;
}
return false;
}
bool empty_queue(QUEUE * pQ) {
if (pQ->front == pQ->rear) {
return true;
}
return false;
}
void traverse_queue(QUEUE *pQ) {
if (empty_queue(pQ)) {
printf("队列为空\n");
}
int p = pQ->front;
while (p != pQ->rear) {
printf("%d ", pQ->pBase[p]);
p = (p + 1) % 6;
}
printf("\n");
return;
}
bool enter_queue(QUEUE *pQ, int val) {
if (full_queue(pQ)) {
return false;
}
pQ->pBase[pQ->rear] = val;
pQ->rear = (pQ->rear + 1) % 6;
return true;
}
bool dequeue(QUEUE *pQ, int *pVal) {
if (empty_queue(pQ)) {
return false;
}
*pVal = pQ->pBase[pQ->front];
pQ->front = (pQ->front + 1) % 6;
return true;
}
2. 链式队列
代码:
# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
# include <stdbool.h>
typedef struct Node {
int data;
struct Node *pNext;
} NODE;
typedef struct Queue {
NODE *pRear;
NODE *pFront;
} QUEUE;
void init(QUEUE *);
bool empty(QUEUE *);
void enter_queue(QUEUE *, int);
void traverse(QUEUE *);
bool dequeue(QUEUE *, int *);
int main() {
QUEUE Q;
int val;
init(&Q);
traverse(&Q);
enter_queue(&Q, 1);
enter_queue(&Q, 2);
enter_queue(&Q, 3);
enter_queue(&Q, 4);
traverse(&Q);
if (dequeue(&Q, &val)) {
printf("出队成功,出队的元素为%d\n", val);
}
traverse(&Q);
return 0;
}
void init(QUEUE *pQ) {
pQ->pRear = (NODE *)malloc(sizeof(NODE));
if (pQ->pRear == NULL) {
printf("分配失败,程序终止!\n");
exit(-1);
}
pQ->pFront = pQ->pRear;
pQ->pFront->pNext = NULL;
return;
}
bool empty(QUEUE *pQ) {
if (pQ->pRear == pQ->pFront) {
return true;
}
return false;
}
void enter_queue(QUEUE *pQ, int val) {
NODE *pNew = (NODE *)malloc(sizeof(NODE));
if (pNew == NULL) {
printf("分配失败!\n");
exit(-1);
}
pNew->data = val;
pNew->pNext = NULL;
pQ->pRear->pNext = pNew;
pQ->pRear = pNew;
return;
}
void traverse(QUEUE *pQ) {
if (empty(pQ)) {
printf("队列为空\n");
}
NODE *p = pQ->pFront->pNext;
while (p != NULL) {
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
return;
}
bool dequeue(QUEUE *pQ, int *pVal) {
if (empty(pQ)) {
return false;
}
NODE *p = pQ->pFront->pNext;
*pVal = p->data;
pQ->pFront->pNext = p->pNext;
free(p);
p = NULL;
return true;
}