队列的特点就是先进先出,后进后出。
(1)创建队列
typedef int QueueDataType;
typedef struct queue {
QueueDataType val;
struct queue* next;
}Qnode;
typedef struct Queue {
Qnode* phead;//队头
Qnode* ptail;//队尾
int size;//队列中的有效数据
}Queue;
(2)初始化队列
//初始化队
void QueueInit(Queue* pq)
{
assert(pq);
pq->phead = pq->ptail = NULL;
pq->size = 0;
}
(3)入队
//入队
void QueuePush(Queue* pq, QueueDataType x)
{
assert(pq);
Qnode* newnode = (Qnode*)malloc(sizeof(Qnode));
if (newnode == NULL)
{
printf("malloc fail\n");
exit(-1);
}
pq->size++;
newnode->val = x;
newnode->next = NULL;
if (pq->phead == NULL)
{
pq->phead = pq->ptail = newnode;
}
else
{
pq->ptail->next = newnode;
pq->ptail = newnode;
}
}
(4)出队
//出队
void QueuePop(Queue* pq) {
assert(pq);
Qnode* next = pq->phead->next;
free(pq->phead);
pq->size--;
pq->phead = next;
}
(5) 获取队首元素
//获取队首元素
QueueDataType QueueFront(Queue* pq) {
assert(pq);
assert(pq->size > 0);
assert(pq->phead);
return pq->phead->val;
}
(6)获取队尾元素
//获取队尾元素
QueueDataType QueueBack(Queue* pq) {
assert(pq);
assert(pq->ptail);
assert(pq->size > 0);
return pq->ptail->val;
}
(7)获取队列有效个数
//获取队列有效个数
int QueueSize(Queue* pq) {
assert(pq);
return pq->size;
}
(8)判断队列是否为空
//判断队列是否为空,为空返回1,非空返回0
bool QueueEmpty(Queue* pq) {
assert(pq);
return pq->size == 0 ? 1 : 0;
}
(9)打印队列
//打印队列
void QueuePrint(Queue* pq) {
assert(pq);
assert(pq->phead);
while (!QueueEmpty(pq))
{
printf("%d\n", pq->phead->val);
QueuePop(pq);
}
}
(10)销毁队列
//销毁队列
void QueueDestory(Queue* pq) {
assert(pq);
Qnode* cur = pq->phead;
while (cur) {
Qnode* next = cur->next;
free(cur);
cur = next;
}
pq->phead = pq->ptail = NULL;
}