队列的特点:先进先出,排队模型
队列有两种:普通队列,循环队列
循环队列最主要的就是要记住什么时候需要判空判满。
队列判空:1、直接调用长度函数,如果长度为0则为空 2、头尾指针指向位置相同,且该位置不存在元素
队列判满:1、直接调用长度函数,如果长度函数为队列能容纳元素最大值则满 2、头尾指针指向位置相同,且该位置存在元素
//first in ;first out; #include#define Max 2 typedef struct queue{ int data[Max];//队列元素 int head;//队头指针 int tail;//队尾指针 }Queue,*XQueue;//定义了该结构体数据类型,还有该结构体指针类型(后面代码没用到) Queue q; void MoveH()//头指针的移动 { q.head++;//后移移位 if(q.head==Max)//判断是否越界 q.head=0; } void MoveT()//尾指针移动 { q.tail++;//后移一位 if(q.tail==Max)//判断是否越界 q.tail=0; } int QueueLength() { int length=0;//长度默认值为0 int head=q.head;//先保留头指针的位置 if(q.head==q.tail&&q.data[q.head]!=0)//如果头指针与尾指针相等,不是队列满了(队头有数据),就是空队列(队头没数据) { // printf("%dn",Max); return Max; } while(q.head!=q.tail) { length++;//长度累加 MoveH();//头指针后移 } q.head=head;//还原头指针的位置 // printf("length:%dn",length); return length; } void CreatQueue()//创建队列(在这个代码里) { q.head=0; q.tail=0; } void DestroyQueue()//销毁置空队列, { while(q.head!=q.tail)//非满队列 { q.data[q.head]=0;//元素为0,表示无值 MoveH();//头指针后移 } if(q.head==q.tail&&q.data[q.head]!=0)//满队列 { q.data[q.head]=0;//元素为0,表示无值 MoveH();//头指针后移 while(q.head!=q.tail) { q.data[q.head]=0;//元素为0,表示无值 MoveH();//头指针后移 } } q.head=0;//头指针置零 q.tail=0;//尾指针置零 } bool QueueEmpty() { if(QueueLength()==0)//长度为0必然为空 return true; return false; } bool EnQueue(int element) { if(QueueLength()==Max)//判满 return false; q.data[q.tail]=element;//插入 MoveT();//尾指针后移 return true; } bool DeQueue(int &element) { if(QueueLength()==0)//判空 return 0; element=q.data[q.head];//取出元素 MoveH();//头指针后移 return true; } void QueueTraverse()//输出队列 { int head=q.head; if(QueueLength!=0)//判空 { //如果是满队列则必须先printf在Move 才能进入while循环;不是满队列也可以这样 printf("%d ",q.data[q.head]); MoveH(); while(q.head!=q.tail) { printf("%d ",q.data[q.head]); MoveH(); } printf("n"); } q.head=head; } int main() { CreatQueue(); EnQueue(1); EnQueue(2); if(EnQueue(3)==false) printf("队满了,%d没有插入!n",3); printf("length:%dn",QueueLength()); QueueTraverse(); int e; DeQueue(e); printf("delete:%dn",e); QueueLength(); printf("length:%dn",QueueLength()); QueueTraverse(); if(QueueEmpty()==false) printf("队列不为空!n"); DestroyQueue(); if(QueueEmpty()==true) printf("队列为空!n"); return 0; }



