队列(c语言描述)

类型名称: 队列
数据对象集: 一个有0个或者多个元素的有穷线性表
操作集: 对于一个长度为长整数MaxSize的队列Q,记队列中的任一元素X,队列的基本操作有:

1:Queue CreateQueue(int MaxSize):生成空队列,其最大长度为:MaxSize;
2:bool IsFull(Queue Q):判断队列Q是否为空,若是返回true,否则返回false;
3:bool AddQ(Queue Q,ElementType X):将元素X压入队列Q。若队列已满,返回false;否则将数据元素X插入队列Q并返回true;
4:bool IsEmpty(Queue Q):判断队列Q是否为空,若是返回true;否则返回false;
5:ElementType DeleteQ(Queue Q):删除并返回队列头元素。若队列为空,返回错误信息;否则将队列头数据元素从队列中删除

队列的顺序存储实现:

结构实现:


typedef int Position;
typedef int ElementType;
typedef struct QNode* PtrToQNode;
struct QNode {
	ElementType* Data;//存储元素的数组
	Position Front, Rear;//队列的头尾指针
	int MaxSize;//队列的最大容量
};

循环队列的创建与插入和删除,判满判空操作的实现:

Queue CreateQueue(int MaxSize) {
	Queue Q = (Queue)malloc(sizeof(struct QNode));//创建队列结构
	Q->Data = (ElementType*)malloc(MaxSize * sizeof(ElementType));//创建队列储存数据的数组结构,并把指针赋值给Data
	Q->Front = Q->Rear=0;//头和尾都指向0
	return Q;
}

bool IsFull(Queue Q) {//判满方法:少用一个元素空间。队满条件:(Rear+1)%数组长度=Front 队列空条件:Rear=Front
	return ((Q->Rear + 1) % Q->MaxSize == Q->Front);
}

bool AddQ(Queue Q, ElementType X) {
	if (IsFull(Q))
	{
		printf("队列满!");
		return false;
	}
	else {
		Q->Rear = ( Q->Rear + 1) % Q->MaxSize;//尾指针向后移动一位
		Q->Data[Q->Rear] = X;//赋值
		return true;
	}
}

bool IsEmpty(Queue Q) {
	return (Q->Front == Q->Rear);
}

ElementType Delete(Queue Q) {
	if (IsEmpty(Q)) {
		printf("队列空!");
		return ERROR;
	}
	else {
		Q->Front = (Q->Front + 1) % Q->MaxSize;
		return Q->Data[Q->Front];
	}
}

队列的链式存储实现:

typedef struct Node* PtrToNode;
struct Node {//队列中的结点
	ElementType Data;
	PtrToNode Next;
};
typedef PtrToNode Position;
typedef struct QNode* PtrToQNode;
struct QNode {
	Position Front, Rear;
	int MaxSize;
};

typedef PtrToQNode Queue;

不带头结点的链式队列操作实例:

bool IsEmpty(Queue Q) {
	//return Q->Front == Q->Rear;//这样比较不是说明队列空,而是队列只有一个元素
	return (Q->Front == NULL);
}

ElementType DeleteQ(Queue Q) {
	Position FirstCell;
	ElementType FrontElem;
	if (IsEmpty(Q))
	{
		printf("队列空!");
		return ERROR;
	}
	else
	{
		/*FirstCell = Q->Front;
		Q->Front = Q->Front->Next;
		FrontElem = FirstCell->Data;
		free(FirstCell);
		return FrontElem;*/
		FirstCell = Q->Front;
		if (Q->Front==Q->Rear)
		{
			Q->Front = Q->Rear = NULL;
		}
		else
		{
			Q->Front = Q->Front->Next;
			FrontElem = FirstCell->Data;
			free(FirstCell);
			return FrontElem;
		}



	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值