队列中的数据遵循先进先出(First In First Out)的原则
队列可以用数组或者链表实现,用数组实现头删需要挪动数据,不容易实现,用链表实现较为简单。
Queue.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int QDataType;
typedef struct QueueNode QueueNode;
typedef struct Queue Queue;
struct QueueNode {
QDataType data;
struct QueueNode* next;
};
struct Queue {
QueueNode* head;
QueueNode* tail;
};
void QueueInite(Queue* pq);
void QueuePush(Queue* pq, QDataType val);
int QueueEmpty(Queue* pq);
void QueuePop(Queue* pq);
QDataType QueueFront(Queue* pq);
QDataType QueueBack(Queue* pq);
void QueueDestory(Queue* pq);
int QueueSize(Queue* pq);
void QueuePrint(Queue* pq);
Queue.c
#include "Queue.h"
void QueueInite(Queue* pq) {
pq->head = NULL;
pq->tail = NULL;
}
void QueuePush(Queue* pq, QDataType val) {
QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
if (newnode == NULL) {
printf("fail\n");
exit(-1);
}
newnode->next = NULL;
newnode->data = val;
if (pq->tail == NULL) {
pq->head = newnode;
pq->tail = newnode;
return;
}
pq->tail->next = newnode;
pq->tail = pq->tail->next;
}
void QueuePop(Queue* pq) {
assert(!QueueEmpty(pq));
if (pq->head->next == NULL) {
free(pq->head);
pq->head = pq->tail = NULL;
return;
}
QueueNode* next = pq->head->next;
free(pq->head);
pq->head = next;
}
int QueueEmpty(Queue* pq) {
return pq->head == NULL && pq->tail == NULL;
}
QDataType QueueFront(Queue* pq) {
assert(!QueueEmpty(pq));
return pq->head->data;
}
QDataType QueueBack(Queue* pq) {
assert(!QueueEmpty(pq));
return pq->tail->data;
}
void QueueDestory(Queue* pq) {
QueueNode* cur = pq->head;
while (cur!=NULL) {
QueueNode* next = cur->next;
free(cur);
cur = next;
}
pq->head = pq->tail = NULL;
}
void QueuePrint(Queue* pq) {
/*QueueNode* cur = pq->head;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");*/
while (!QueueEmpty(pq)) {
printf("%d ", QueueFront(pq));
QueuePop(pq);
}
printf("\n");
}
int QueueSize(Queue* pq) {
int size = 0;
QueueNode* cur = pq->head;
while (cur != NULL) {
size++;
cur = cur->next;
}
return size;
}