c/c++ 数据结构 顺序队列

顺序对列的数据处理方式就像独木桥,具有先进先出,后进后出的特点。

顺序对列的序列结构:

#include<stdio.h>
#include<malloc.h>
#define Maxsize 20

typedef struct {
	int data[Maxsize];
	int front, rear;
}SqQueue;

 其中,front表示队首,进行出队操作;rear表示队尾,进行入队操作。

 

初始化顺序队列:令其front和rear均为-1

void InitSqQueue(SqQueue*& Q)
{
	Q = (SqQueue*)malloc(sizeof(SqQueue));
	Q->front = Q->rear = -1;
}

 

销毁顺序队列:free()

void DestroySqQueue(SqQueue*& Q)
{
	free(Q);
}

判断顺序队列是否为空:

bool EmptySqQueue(SqQueue* Q)
{
	return Q->front == Q->rear;
}

在队尾插入元素(若队满则返回假):

bool PushSqQueue(SqQueue*& Q, int a)
{
	if (Q->rear == Maxsize-1)
		return false;
	else
	{
		Q->rear++;
		Q->data[Q->rear] = a;
	}
}

在队首删除元素(若队空则返回假):

bool PullSqQueue(SqQueue*& Q, int& a)
{
	if (Q->front == Q->rear)
		return false;
	else
	{
		a = Q->data[Q->front + 1];
		Q->front++;
		return true;
	}
}

输出顺序队列元素:

void DispSqQueue(SqQueue* Q)
{
	if (EmptySqQueue(Q))
		printf("空的\n");
	else
	{
		for (int i = Q->front+1; i < Q->rear + 1; i++)
		{
			printf("%d ", Q->data[i]);
		}
		printf("\n");
	}
}

最后在main()函数上实现

int main()
{
	SqQueue* Q;
	InitSqQueue(Q);
	if (EmptySqQueue)
		printf("栈为空\n");
	else
		printf("栈不为空\n");
	printf("\n开始进栈\n");
	for (int i = 0; i < 8; i++)
	{
		printf("元素%d进栈:",i);
		PushSqQueue(Q, i);
		DispSqQueue(Q);
	}
	printf("\n开始出栈\n");
	for (int i = 0; i < 4; i++)
	{
		int value = 0;
		PullSqQueue(Q, value);
		printf("元素%d出栈:", value);
		DispSqQueue(Q);
	}
	DestroySqQueue(Q);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值