数据结构:顺序队列

1.头文件(sqqueue.h)

#pragma once
#define MAXSIZE 100
typedef int ElemType;

typedef struct SqQueue
{
	ElemType base[MAXSIZE];
	int front;//队头指针,实际是下标
	int rear;//队尾指针,实际是下标,当前可以存放数据的下标
}SqQueue, * PSqQueue;
//队列初始化
void InitQueue(PSqQueue pq);

//入队
bool Push(PSqQueue pq, ElemType val);

//判空
bool IsEmpty(PSqQueue pq);

//获取队头元素,但不删除
bool GetHead(PSqQueue pq, ElemType* rtval);

//出队,获取队头元素,且删除
bool DeQueue(PSqQueue pq, ElemType* rtval);

//销毁
void Destroy(PSqQueue ps);

2.函数实现文件(sqqueue.cpp)

#include<stdio.h>
#include<assert.h>
#include"sqqueue.h"
//队列初始化
void InitQueue(PSqQueue pq)
{
	assert(pq != NULL);
	if (pq == NULL)
		return;
	//pq->base;//不需要处理
	pq->front = 0;
	pq->rear = 0;
}
//判满
static bool IsFull(PSqQueue pq)
{
	return (pq->rear + 1) % MAXSIZE == pq->front;
}

//入队
bool Push(PSqQueue pq, ElemType val)
{
	if (IsFull(pq))
		return false;
	pq->base[pq->rear] = val;
	//pq->rear++;//error,需要环形处理
	pq->rear = (pq->rear + 1) % MAXSIZE;
	return true;
}

//判空
bool IsEmpty(PSqQueue pq)
{
	return pq->front == pq->rear;

}

//获取队头元素,但不删除
bool GetHead(PSqQueue pq, ElemType* rtval)
{
	if (IsEmpty(pq))
		return false;
	*rtval = pq->base[pq->front];
}

//出队,获取队头元素,且删除
bool DeQueue(PSqQueue pq, ElemType* rtval)
{
	if (IsEmpty(pq))
		return false;
	*rtval = pq->base[pq->front];

	pq->front = (pq->front + 1) % MAXSIZE;//环形处理
	return true;
}

//销毁
void Destroy(PSqQueue ps)
{
	return;
}

3.测试文件(test.cpp)

#include <stdio.h>
#include "sqqueue.h"

int main()
{
	SqQueue sq;//sizeof(sq)==408

	InitQueue(&sq);

	for (int i = 0; i < 20; i++)
	{
		Push(&sq, i);
	}

	int val;
	while (!IsEmpty(&sq))
	{
		DeQueue(&sq, &val);
		printf("%d\n", val);
	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值