栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

队列的顺序表示和实现

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

队列的顺序表示和实现

队列的顺序表示和实现:

编写一个程序实现顺序队列的各种基本运算(采用循环队列),并在此基础上设计一个主程序,完成如下功能:

  1. 初始化队列
  2. 入队
  3. 出队
  4. 判断队列是否为空
  5. 清空队列
  6. 销毁队列
  7. 获取队列长度
  8. 获取队头元素
  9. 遍历队列
代码(C语言):
//循环队列及操作的算法实现(front为队头元素的当前位置,rear为队尾元素的下一个位置)
#include
#include
#define INITSIZE 10 
#define INCREMENT 5 
typedef int ElemType;
typedef struct
{
	ElemType* data;
	int front;
	int rear;
	int QueueSize; 
} SqQueue;


int InitQueue(SqQueue* Q)
{
	
	Q->data = (ElemType*)malloc(INITSIZE * sizeof(ElemType));
	if (!Q->data) return 0; 
	Q->front = Q->rear = 0;
	Q->QueueSize = INITSIZE;
	return 1; //初始化成功则返回1
}


void DestoryQueue(SqQueue* Q)
{
	if (Q->data)
		free(Q->data);
	Q->data = NULL;
	Q->QueueSize = Q->front = Q->rear = 0;
}


void ClearQueue(SqQueue* Q)
{
	Q->front = Q->rear = 0;
}


int QueueEmpty(SqQueue Q)
{
	if (Q.front == Q.rear) return 1; //返回1代表为空队列,返回0代表不为空队列
	else return 0;
}


int GetHead(SqQueue Q, ElemType* e)
{
	if (Q.front == Q.rear) return 0;
	*e = Q.data[Q.front];
	return 1;
}


int QueueLength(SqQueue Q)
{
	return (Q.rear - Q.front + Q.QueueSize) % Q.QueueSize;
}


void QueueTraverse(SqQueue Q)
{
	int i = Q.front; 
	while (i != Q.rear)
	{
		printf("%d ", Q.data[i]);
		i = (i + 1) % Q.QueueSize;
	}
	printf("n");
}


int EnQueue(SqQueue* Q, ElemType e)
{
	if ((Q->rear + 1) % Q->QueueSize == Q->front)
	{
		Q->data = (ElemType*)realloc(Q->data, sizeof(ElemType) * (Q->QueueSize + INCREMENT));
		Q->QueueSize += INCREMENT;
	}
	if (!Q->data) return 0;
	Q->data[Q->rear] = e;
	Q->rear = (Q->rear + 1) % Q->QueueSize;
	return 1;
}


int DeQueue(SqQueue* Q, ElemType* e)
{
	if (Q->front == Q->rear) return 0; //队列为空则返回0,代表出队失败
	*e = Q->data[Q->front];
	Q->front = (Q->front + 1) % Q->QueueSize;
	return 1;
}


int main(void)
{
	int i = 0, m = 0, k = 0, n = 0;
	ElemType d = 0;
	SqQueue Q;
	InitQueue(&Q);
	printf("输入队列元素个数:");
	scanf("%d", &n);
	printf("执行入队操作:");
	for (i = 0; i < n; i++)
	{
		EnQueue(&Q, i + 1);
	}
	printf("队列为:");
	QueueTraverse(Q);
	printf("队列长度:%dn", QueueLength(Q));
	k = QueueLength(Q);
	printf("连续%d次由队头删除元素,由队尾插入元素:n", k / 2);
	for (m = 1; m <= k / 2; m++)
	{
		DeQueue(&Q, &d);
		printf("删除的元素是%d,请输入要插入的元素:", d);
		scanf("%d", &d);
		EnQueue(&Q, d);
	}
	printf("新队列为:");
	QueueTraverse(Q);
	n = GetHead(Q, &d);
	if (n) printf("队头元素的值:%dn", d);
	printf("清空队列n");
	ClearQueue(&Q);
	printf("清空队列后,队列是否为空n=%d(1,为空;0,不为空)n", QueueEmpty(Q));
	system("pause");
	return 0;
}
执行结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/347326.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号