静态数组实现队列

前言
与线性表(链表)、栈类似,队列也有顺序存储和链式存储两种存储方法。以顺序储存为例。今天主要讲静态数组实现队列的过程。日常生活中,去超市购物,结账,去售票处买票,都是典型的队列。

概念
队列是一种先进先出的数据结构。队列简称队,只允许在表的尾端进行插入,而在表的首端进行删除。向队列中插入元素称为入队;删除元素称为出队。

在这里插入图片描述
它需要两个指针,一个指向队头(front),一个指向队尾(rear),这样才能方便地进行入队或出队操作。

静态数组实现队列
本文选择静态数组是因为操作简便,效率高。这正是数组的优点,接下来实现

#include <stdio.h>
#include <string.h>

#define QUE_SIZE 10  //最大队列长度+1 ,实际长度为9

typedef struct QueueInfo
{
	int front; //队头
	int tail;//队尾
	int queueArr[QUE_SIZE];

}QUEUE;

//判断队列是否为满

int QueueIsFull(QUEUE *queue)
{
	if ((queue->tail+2)% QUE_SIZE == queue->front) //队列满的条件
	{
		printf("queue is full\n");
		return -1;
	}

	else //队列不为满
		return 0;

}

//判断队列是否为空

int QueueIsEmpty(QUEUE *queue)
{
	if ((queue->tail + 1) % QUE_SIZE == queue->front) //为空的条件
	{
		printf("queue is empty\n");
		return -1;
	}

	else
		return 0;
}

//入队

int QueueInsert(QUEUE *queue, int value)
{
	if (QueueIsFull(queue)) //如果尾部入队失败,即队列已满
		return -1;

	queue->tail = (queue->tail+1)%QUE_SIZE;//更新队尾元素
	queue->queueArr[queue->tail] = value; //插入新的队尾元素

	printf("insert %d  to %d\n",value,queue->tail);	

	return 0;
}

//出队

int QueueDelete(QUEUE * queue, int *value)
{
	if (QueueIsEmpty(queue))
		return -1;

		*value = queue->queueArr[queue->front];//删除头存放在value中
		 printf("delete value from front %d  is %d\n",queue->front,*value);
		queue->front = (queue->front + 1)%QUE_SIZE;//更新头指针		

		return 0;
}


int main(int argc, char const *argv[])
{
	
	int value = 0;
	int i = 0;
	int j = 0;
	QUEUE queue;

    memset(&queue,0,sizeof(queue));
    queue.front = 1;
    queue.tail = 0;

    //假设入队位12个数据,则只有前10个在队内,剩下3个入队失败
    for (i = 0; i < 12; i ++)
    	QueueInsert(&queue,i);

    for (i = 0; i < 12; i++) //出队数据,最后3个出队失败
    	QueueDelete(&queue,&i);

	return 0;
}

输出结果:
在这里插入图片描述程序定一个队列结构体,包含存储队头位置和队尾位以及队列容量数组。静态数组实现队列要考虑队空和对满的区别,以及考虑数据搬移的性能影响。

队列定义说明:

1.队列为空的条件: (queue->tail + 1) % QUE_SIZE == queue->front
2.队列满的条件: (queue->tail+2)% QUE_SIZE == queue->front
3.更新头指针:queue->front = (queue->front + 1)%QUE_SIZE;
4.更新尾指针:queue->tail = (queue->tail+1)%QUE_SIZE;

发布了71 篇原创文章 · 获赞 42 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/chen1415886044/article/details/102691981