#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);
}
}
int main()
{
QueueHead myhead;
Init_Queue(&myhead);
for (int i = 0; i < 10; ++i)
{
Push_Back(&myhead, i);
}
Print_Queue(&myhead);
printf(" Lenget=%d\n", Get_Length(&myhead));
int n = 0;
Pop_Front(&myhead, n);
Print_Queue(&myhead);
printf(" Length=%d\n", Get_Length(&myhead));
Clear_Queue(&myhead);
Print_Queue(&myhead);
printf(" Length=%d\n", Get_Length(&myhead));
return 0;
}
链式队列的实现
最新推荐文章于 2022-10-09 17:39:55 发布