数据结构(C语言):顺序队列的创建、入队、出队、销毁等操作

seqQueue.h

#ifndef _SEQ_QUEUE_H_
#define _SEQ_QUEUE_H_

#include <stdio.h>
#include <stdlib.h>


typedef int DataType;

typedef struct list
{
	DataType *pBase;
	int front;
	int rear;
}SeqQueue;

#define SEQ_QUEUE_MAX_SIZE 10


extern SeqQueue *createSeqQueue();
extern int isFullSeqQueue(SeqQueue *pList);
extern int isEmptySeqQueue(SeqQueue *pList);
extern void showSeqQueue(SeqQueue *pList);
extern int enterSeqQueue(SeqQueue *pList,DataType data);
extern int outSeqQueue(SeqQueue *pList,DataType *poutdata);
extern int getLenthSeqQueue(SeqQueue * pList);
extern void destroySeqQueue(SeqQueue **pList);





#endif

seqQueue.c


#include "seqQueue.h"


/*创建顺序队列*/
SeqQueue *createSeqQueue()
{
	SeqQueue *pList = malloc(sizeof(SeqQueue));
	if(NULL == pList)
	{
		perror("createSeqQueue malloc error\n");
		return NULL;
	}

	pList->front = 0;
	pList->rear = 0;
	pList->pBase = malloc(sizeof(DataType) * SEQ_QUEUE_MAX_SIZE);
	if(NULL == pList->pBase)
	{
		perror("pBase malloc error!\n");
		return NULL;
	}

	return pList;
}

/*判断是否为满队列*/
int isFullSeqQueue(SeqQueue *pList)
{
	return (pList->rear + 1) % SEQ_QUEUE_MAX_SIZE == pList->front;
}

/*判断是否为空队列*/
int isEmptySeqQueue(SeqQueue *pList)
{
	return pList->front == pList->rear;
}

/*遍历*/
void showSeqQueue(SeqQueue *pList)
{
	int i = 0;
	i = pList->front;

	while(i != pList->rear)
	{
		printf("%d ",pList->pBase[i]);
		i = (i+1) % SEQ_QUEUE_MAX_SIZE;
	}
	printf("\n");
}

/*入队*/
int enterSeqQueue(SeqQueue *pList,DataType data)
{
	if(isFullSeqQueue(pList))
	{
		return 0;
	}

	pList->pBase[pList->rear] = data;
	pList->rear = (pList->rear + 1) % SEQ_QUEUE_MAX_SIZE;
	
	return 0;
}

/*出队*/
int outSeqQueue(SeqQueue *pList,DataType *poutdata)
{
	if(isEmptySeqQueue(pList))
	{
		return 0;
	}
	if(poutdata != NULL)
	{
		*poutdata = pList->pBase[pList->front];
	}
	pList->front = (pList->front + 1) % SEQ_QUEUE_MAX_SIZE;

	return 0;
}

/*获取队列长度*/
int getLenthSeqQueue(SeqQueue * pList)
{
	return (pList->rear - pList->front + SEQ_QUEUE_MAX_SIZE) % SEQ_QUEUE_MAX_SIZE;
}

/*销毁队列*/
void destroySeqQueue(SeqQueue **pList)
{
	free((*pList)->pBase);
	free(*pList);
	*pList = NULL;
}

main.c

#include "seqQueue.h"




int main(int argc, const char *argv[])
{
	SeqQueue *pList = NULL;
	pList = createSeqQueue();

	int i = 0;
	for(i = 0;i < 10;i++)
	{
		enterSeqQueue(pList,i);	
	}
	showSeqQueue(pList);

	outSeqQueue(pList,NULL);
	showSeqQueue(pList);

	enterSeqQueue(pList,9);	
	showSeqQueue(pList);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值