提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

能够熟练掌握顺序队列,掌握它的特点,方便后面用来解决某些问题,例如二叉数的层序遍历;

提示:以下是本篇文章正文内容,下面案例可供参考

*在这里插入代码片*

一、什么是顺序队列

顺序队列是队列的顺序存储结构,顺序队列实际上是运算受限的顺序表。和顺序表一样,顺序队列用一个向量空间来存放当前队列中的元素。由于队列的队头和队尾的位置是变化的,设置两个指针front和rear分别指示队头元素和队尾元素在向量空间中的位置,它们的初值在队列初始化时均应设置为0。

在这里插入图片描述

二、代码实现

1.创建顺序表

代码如下(示例):

typedef struct Sequeue
{
	elemstyle* data;
	int top;
	int rear;
}SeqQueue;
//队列初始化;
SeqQueue* Init_SeqQueue(SeqQueue* ps)
{
	ps->data = (elemstyle*)malloc(sizeof(elemstyle));
	ps->rear = ps->top = 0;
	return ps;
}

2.入队,出队操作

代码如下(示例):

//入队;
void pushSeqQueue(SeqQueue* ps, int val)
{
	assert(ps != NULL);
	ps->data[ps->rear++] = val;
}
//出队;
int popSeqQueue(SeqQueue* ps)
{
	assert(ps != NULL);
	if (ps->top != ps->rear)
	{
		printf("%5d", ps->data[ps->top++]);
	}
	else
	{
		return false;
	}
}

该处使用的url网络请求的数据。


3.源代码

//顺序队列;
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<windows.h>
#define maxsize 10
#define ok 1
#define erro -1
#define true 2
#define false -2
typedef int elemstyle;
//顺序队列
typedef struct Sequeue
{
	elemstyle* data;
	int top;
	int rear;
}SeqQueue;
//队列初始化;
SeqQueue* Init_SeqQueue(SeqQueue* ps)
{
	ps->data = (elemstyle*)malloc(sizeof(elemstyle));
	ps->rear = ps->top = 0;
	return ps;
}
//入队;
void pushSeqQueue(SeqQueue* ps, int val)
{
	assert(ps != NULL);
	ps->data[ps->rear++] = val;
}
//出队;
int popSeqQueue(SeqQueue* ps)
{
	assert(ps != NULL);
	if (ps->top != ps->rear)
	{
		printf("%5d", ps->data[ps->top++]);
	}
	else
	{
		return false;
	}
}
//判空;
int emptySeqQueue(SeqQueue* ps)
{
	assert(ps != NULL);
	if (ps->rear - ps->top == 0)
	{
			return true;
    }
	else
	{
		return false;
	}
}
//队列长度;
int lengthSeqQueue(SeqQueue* ps)
{
	assert(ps != NULL);
	return (ps->rear - ps->top );   //rear和top代表的是下标;
}
//获取队头元素;
void frontSeqQueue(SeqQueue* ps)
{
	assert(ps != NULL);
	int length=lengthSeqQueue(ps);
	if(length!=0)
	printf("队头元素为:%5d\n", ps->data[ps->top]);
	else
	{
		printf("队列为空,无法获取队头元素;\n");
	}
}
//调试函数;调试的时候去掉过度符
/*
int main(void)
{
	SeqQueue ps;
	//队列初始化;
	Init_SeqQueue(&ps);
	//入队;
	for (int i = 0; i < maxsize; i++)
	{
		pushSeqQueue(&ps, i);
	}
	//出队;
	for (int i = 0; i < maxsize; i++)
	{
		popSeqQueue(&ps);
	}
}
*/`

总结

顺序队列是一种很简单的数据存储结构,和顺序表大同小异。以上是我打的代码,希望能够帮到你。
在这里插入图片描述

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐