版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaofen_7/article/details/82053552
队列:先进先出
实现方式 | 顺序 | 链接 |
---|---|---|
基本结构 | 数组 | 节点,单链表 |
细化分类 | 简单队列,循环队列 | 无 |
顺序存储—简单对列:
const int maxsize=20; //实现
typedef struct
{
DateType data[maxsize];
int front,rear;
}SeqQue;
SeqQue SQ;
void InitQueue(SeqQue SQ) //初始化
{
SQ.front=0;
SQ.rear=0;
}
int EmptyQueue(SeqQue SQ) //判空
{
if (SQ.rear==SQ.front)
{
return 1; //队列为空,返回1
}
else
{
return 0; //对列不为空,返回0
}
}
int EnQueue(SeqQue SQ,DataType x) //入队
{
if(SQ.rear == SQ.front) //***************************不能准确表示是满还是空,所以出现循环队列
{
error("对列满");
return 0; //对列满,入队失败
}
else
{
SQ.front=(SQ.front+1);
return 1;
}
}
int OutQueue(SeqQue SQ) //出对列
{
if(EmptyQueue(SQ))
{
error("队列为空"); //队列为空,出队失败
return 0;
}
else
{
SQ.front=(SQ.front+1); //不为空,出对列
return 1;
}
}
DataType GetHead(SeqQue SQ) //取对首元素
{
if (EmptyQueue(SQ))
{
return NULLData;
}
else
{
return SQ.data{(SQ.front+1)}
}
}
顺序存储—循环对列:
const int maxsize=20; //实现
typedef struct
{
DateType data[maxsize];
int front,rear;
}CycQue;
CycQue CQ;
void InitQueue(CycQue CQ) //初始化
{
CQ.front=0;
CQ.rear=0;
}
int EmptyQueue(CycQue CQ) //判空
{
if (CQ.rear==CQ.front)
{
return 1; //队列为空,返回1
}
else
{
return 0; //对列不为空,返回0
}
}
int EnQueue(CycQue CQ,DataType x) //入队
{
if((CQ.rear+1) % maxsize == CQ.front)
{
error("对列满");
return 0; //对列满,入队失败
}
else
{
CQ.front=(CQ.front+1) % maxsize;
return 1;
}
}
int OutQueue(CycQue CQ) //出对列
{
if(EmptyQueue(CQ))
{
error("队列为空"); //队列为空,出队失败
return 0;
}
else
{
CQ.front=(CQ.front+1) % maxsize; //不为空,出对列
return 1;
}
}
DataType GetHead(CycQue CQ) //取对首元素
{
if (EmptyQueue(CQ))
{
return NULLData;
}
else
{
return CQ.data{(CQ.front+1) % maxsize }
}
}
链接存储—简单队列
typedef struct //定义节点数据类型
{
DataType data;
struct LinkQueueNode *next;
}LinkQueueNode;
LinkQueueNode LkQueNode;
typedef struct //定义队列数据类型
{
LkQueNode *front,*rear;
}LkQue;
LkQue LQ;
void InitQueue(LKQue *LQ) //初始化
{
LkQueNode *temp;
temp=(LkQueNode *)malloc(sizeof(LkQueNode));
LQ->front=temp;
LQ->rear=temp;
(LQ->front)->next=NULL;
}
int EmptyQueue(LKQue LQ) //判空
{
if(LQ.rear==LQ.front)
{
return 1;
}
else
{
return 0;
}
}
void EnQueue(LkQue *LQ , DateType x) //入队列
{
LkQueNode *temp;
temp=(LkQueNode *)malloc(sizeof(LkQueNode))
temp->data=x;
temp->next=NULL;
(LQ->rear)->next=temp; //将节点temp的地址赋值给头指针的指针域
LQ->rear=temp; //队列的尾指针指向temp
}
OutQueue(LKQue *LQ) //出对列
{
LkQueNode *temp; //*temp代表指针temp所指向的节点,temp代表指针
if(EmptyQueue(CQ))
{
error("队空");
return 0;
}
else
{
temp=(LQ->front)->next; //将temp指向首节点
(LQ->front)->next=temp->next; //将*temp的下一个节点的指针域赋值给头结点的
if (temp->next==NULL) //无首节点
{
LQ.rear=LQ->front;
free(temp);
return 1;
}
}
}
DataType GetHead(LkQue LQ) //取队首元素
{
if(EmptyQueue(CQ))
{
return NULLData; //队列为空
}
else
{
temp=LQ.front->next; //将队头节点的指针域赋值给指针temp
return temp->data; //将首节点的的值返回
}
}