我尾部进入,头部出
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node* next;
}QueueNode;
typedef struct Head
{
struct Node* front;
struct Node* rear;
int cursize;
}QueueHead;
QueueNode* BuyNode()
{
QueueNode* s = (QueueNode*)malloc(sizeof(QueueNode));
if (nullptr == s) exit(1);
memset(s, 0, sizeof(QueueNode));
return s;
}
void Init_Queue(QueueHead* phead)
{
assert(phead != nullptr);
memset(phead, 0, 12);
}
bool Push_Back(QueueHead* phead, ElemType val)
{
assert(phead != nullptr);
QueueNode* pnewnode = BuyNode();
pnewnode->data = val;
if (nullptr == phead->front)
{
phead->front = pnewnode;
phead->rear = pnewnode;
phead->cursize += 1;
}
else
{
phead->rear->next = pnewnode;
phead->rear = pnewnode;
phead->cursize += 1;
}
return true;
}
bool Is_Empty(QueueHead* phead)
{
assert(phead != nullptr);
return phead->front == nullptr;
}
bool Pop_Front(QueueHead* phead, ElemType& val)
{
assert(phead != nullptr);
if (Is_Empty(phead)) exit(1);
if (nullptr == phead->front->next)
{
val = phead->front->data;
free(phead->front);
phead->front = nullptr;
phead->rear = nullptr;
phead->cursize -= 1;
}
else
{
QueueNode* q = phead->front;
val = q->data;
phead->front = q->next;
free(q);
q = nullptr;
phead->cursize -= 1;
}
}
int Get_Length(QueueHead* phead)
{
assert(phead != nullptr);
return phead->cursize;
}
void Print_Queue(QueueHead* phead)
{
assert(phead != nullptr);
QueueNode* p = phead->front;
while (p != nullptr)
{
printf("%3d", p->data);
p = p->next;
}
printf("\n");
}
void Clear_Queue(QueueHead* phead)
{
assert(phead != nullptr);
int n = 0;
while (phead->front != nullptr)
{
Pop_Front(phead, n);
}
}