【基础算法】-队列

1.队列的介绍

队列介绍:先进先出(FIFO)-先进队列的元素先出队列。来源于我们生活中的队列(先排队的先办完事)。

队尾(tail)——允许插入的一端

队头(head)——允许删除的一端

 队列有下面几个操作:

 InitQueue()   ——初始化队列

 EnQueue()        ——进队列

 DeQueue()        ——出队列

 IsQueueEmpty()——判断队列是否为空 2

 IsQueueFull()    ——判断队列是否已满

队列可以由数组和链表两种形式实现队列操作(c语言),下面仅以数组为例:

2.C语言版队列的实现

(1)队列的数据结构

typedef struct queue
{
       int queuesize;   //数组的大小
       int head, tail;  //队列的头和尾下标
       int *q;          //数组头指针
}Queue;

(2)初始化队列

void InitQueue(Queue *Q)
{
       Q->queuesize = 8;
       Q->q = (int *)malloc(sizeof(int) * Q->queuesize);
//分配内存
       Q->tail = 0;
       Q->head = 0;
}

(3)进队列

void EnQueue(Queue *Q, int key)
{
       int tail = (Q->tail+1) % Q->queuesize;
//取余保证,当quil=queuesize-1时,再转回0
       if (tail == Q->head)                  
//此时队列没有空间
       {
           printf("the queue has been filled full!");
       }
       else
       {
           Q->q[Q->tail] = key;
           Q->tail = tail;
       }
}

(4)出队列

int DeQueue(Queue *Q)
{
       int tmp;
       if(Q->tail == Q->head)     //判断队列不为空
       {
           printf("the queue is NULL\n");
       }
       else
       {
           tmp = Q->q[q->head];
           Q->head = (Q->head+1) % Q->queuesize;
       }
       return tmp;
}

(5)判断队列是否为空

int IsQueueEmpty(Queue *Q)
{
       if(Q->head == Q->tail)
       {
           return 1;
       }
       else
       {
           return 0;
       }
}

(6)判断队列是否已满

int IsQueueFull(Queue *Q)
{
   if((Q->tail+1)% Q->queuesize == Q->head)
   {
       return 1;
   }
   else
   {
       return 0;
   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值