码迷,mamicode.com
首页 > 其他好文 > 详细

队列顺序存储(循环队列)

时间:2015-04-17 11:24:32      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

/*
 * 2015年4月17日 09:07:17
 * 目的:实现循环队列(顺序存储结构),本来我想要在实现循环队列之前
 * 先实现队列的顺序存储,但是这种算法有很大的缺点
 * 首先会造成假溢出现象
*/

/*
 * 解决队列的相关问题,就是怎么判断队列是否满了或者空了
 * 第一种方法:
 * 我们在队满和对空时都是real = front;这样就不够具体,容易出错
 * 所以我们采取牺牲一个存储单元,这样对空时,判断是:real == front
 * 队满的操作是:(real+1)%maxSize == front
 * 第二种方法:就是增加一个变量来表示队列中元素的个数,size
 * 这里我使用第一种方法。
*/

# include <stdio.h>
# define maxSize 50

struct sqQueue{
	int *data;
	int front; //对头指针
	int rear; //队尾指针
};

//初始化
void initQueue(sqQueue *queue)
{
	queue->data = new int[maxSize];
	queue->front = queue->rear = 0; //初始化队首和队尾指针
}

//判断队列是否为空
bool isEmpty(sqQueue *queue)
{
	if(queue->front == queue->rear)
		return true;
	else
		return false;
}

//判断队列是否满了
bool isFill(sqQueue *queue)
{
	if(queue->front == (queue->rear+1) % maxSize)
		return true;
	else
		return false;
}

//入队列
void enterQueue(sqQueue *queue,int value)
{
	if(isFill(queue))
	{
		printf("队列已经满了,无法再插入其他数!\n");
	}
	else
	{
		queue->data[queue->rear] = value; //给队尾指针赋值
		queue->rear = (queue->rear+1) % maxSize; //给队尾指针加1取模
	}
}

//出队列
void outofQueue(sqQueue *queue,int *value)
{
	if(isEmpty(queue))
	{
		printf("队列为空!,无法出队列.\n");
	}
	else
	{
		*value = queue->data[queue->front];
		queue->front = (queue->front+1) % maxSize;
	}
}

//输出队列
void printQueue(sqQueue *queue)
{
	if(isEmpty(queue))
		printf("队列为空!,无法出队列.\n");
	else
	{
		printf("队列的元素是:\n");
		if(queue->rear < queue->front)
		{
			for(int i = queue->front;i <maxSize;i++)
			{
				printf("%4d ",queue->data[i]);
				if((i+1) % 10 == 0)
					printf("\n");
			}

			for(int j = 0;j < queue->rear;j++)
			{
				printf("%4d ",queue->data[i]);
				if((i+1) % 10 == 0)
					printf("\n");
			}
		}
		else
		{
			for(int i = queue->front;i < queue->rear;i++)
			{
				printf("%4d ",queue->data[i]);
				if((i+1) % 10 == 0)
					printf("\n");
			}
			printf("\n");
		}
	}
}

int main()
{
	sqQueue queue;
	initQueue(&queue);
	for(int i = 1;i < 20;i++)
		enterQueue(&queue,i);
	printQueue(&queue);
	int value ;
	outofQueue(&queue,&value);
	printf("出队列的元素是:%d\n",value);
	printQueue(&queue);
	return 0;
}

队列顺序存储(循环队列)

标签:

原文地址:http://blog.csdn.net/u011257298/article/details/45093623

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!