队列
队列也是数据结构中的一种结构,和栈不同的是,队列是一端进行插入,另一端进行删除
队列的一种典型应用场景就是医院或者银行里面的打票机,刷身份证录入系统就相当于数据的插入,取票就相当与删除数据
与栈的实现类似,队列同样可以用顺序表或链表实现,但是由于队列是一端进行插入,一端删除,对于删除,用顺序表的话比较麻烦,还要挪动数据,所以这里运用链表比较方便
队列的实现
头文件
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
typedef int Sdatetype;
typedef struct Sequence
{
Sdatetype x;
struct Sequence* next;
}Qnode;
typedef struct Queue
{
Qnode* phead;
Qnode* ptail;
int size;
}Queue;
//初始化
void Queueinit(Queue* pq);
//销毁
void Queuedestory(Queue* pq);
//插入数据
void Queuepush(Queue* pq, Sdatetype x);
//删除数据
void Queuepop(Queue* pq);
//尾节点值
Sdatetype Queueback(Queue* pq);
//头节点值
Sdatetype Queuefront(Queue* pq);
//大小
int Queuesize(Queue* pq);
//判断是否为空
bool Queueempty(Queue* pq);
源文件
#include"Sequence.h"
//初始化
void Queueinit(Queue* pq)
{
assert(pq);//判断是否为空指针,空指针是不指向任何数据的指针
pq->phead = pq->ptail = NULL;
pq->size = 0;
}
//销毁
void Queuedestory(Queue* pq)
{
assert(pq);
Qnode* pcur = pq->phead;
while (pcur)
{
Qnode* next = pcur->next;
free(pcur);
pcur = next;
}
pq->phead = pq->ptail = NULL;
pq->size = 0;
}
//插入数据
void Queuepush(Queue* pq, Sdatetype x)
{
assert(pq);
Qnode* newnode = (Qnode*)malloc(sizeof(Qnode));
if (newnode == NULL)
{
perror("malloc");
return;
}
newnode->x = x;
newnode->next = NULL;
if (pq->ptail == NULL)
{
pq->phead = pq->ptail = newnode;
}
else
{
pq->ptail->next = newnode;
pq->ptail = newnode;
}
pq->size++;
}
//删除数据
void Queuepop(Queue* pq)
{
assert(pq);
assert(pq->phead);
if (pq->phead->next == NULL)
{
free(pq->phead);
pq->phead = pq->ptail = NULL;
}
else
{
Qnode* next = pq->phead->next;
free(pq->phead);
pq->phead = next;
}
pq->size--;
}
//尾节点值
Sdatetype Queueback(Queue* pq)
{
assert(pq);
assert(pq->ptail);
return pq->ptail->x;
}
//头节点值
Sdatetype Queuefront(Queue* pq)
{
assert(pq);
assert(pq->phead);
return pq->phead->x;
}
//大小
int Queuesize(Queue* pq)
{
assert(pq);
return pq->size;
}
//判断是否为空
bool Queueempty(Queue* pq)
{
assert(pq);
if (pq->ptail == NULL)
{
return true;
}
return false;
}
测试文件
#include"Sequence.h"
int main()
{
Queue queue;
Queueinit(&queue);
Queuepush(&queue, 1);
Queuepush(&queue, 2);
Queuepush(&queue, 3);
Queuepush(&queue, 4);
while (queue.size)
{
printf("%d ", Queuefront(&queue));
Queuepop(&queue);
}
Queuedestory(&queue);
return 0;
}