学习笔记之数据结构篇-05顺序队列

/*顺序队列的简要实现
 *
 *
 */
#include <stdio.h>    
#include <stdlib.h>    

#define MAXSIZE 20
struct QueueArray;
typedef int ElementType;
typedef struct QueueArray* PtrToQueue;
typedef PtrToQueue Queue;

struct QueueArray{
	ElementType data[MAXSIZE];
	int front;
	int rear;
};

Queue InitQueue();/*初始化队列*/
void ClearQueue(Queue Q);/*清空队列*/
void QueueEmpty(Queue Q);/*检查队列是否为空*/
int QueueLength(Queue Q);/*获取队列长度*/
int GetHead(Queue Q);/*获取队列头元素*/
int EnQueue(Queue Q, ElementType e);/*入列*/
int DeQueue(Queue Q);/*出列*/

/*初始化队列*/
Queue InitQueue(){
	Queue Q = malloc(sizeof(struct QueueArray));
	Q->front = 0;
	Q->rear = 0;
	return Q;
}

/*清空队列*/
void ClearQueue(Queue Q){
	Q->front = Q->rear = 0;
}

/*检查队列是否为空*/
void QueueEmpty(Queue Q){
	if (Q->front == Q->rear)
		printf("\n队列为空\n");
	else
		printf("\n队列不为空\n");
}

/*获取队列长度*/
int QueueLength(Queue Q){
	return  (Q->rear - Q->front + MAXSIZE) % MAXSIZE;
}

/*获取队列头元素*/
int GetHead(Queue Q){
	if (Q->front == Q->rear)
		return NULL; 
	return Q->data[Q->front];
}

/*入列*/
int EnQueue(Queue Q, ElementType e){
	if ((Q->rear + 1) % MAXSIZE == Q->front)	
		return NULL;
	Q->data[Q->rear] = e;			
	Q->rear = (Q->rear + 1) % MAXSIZE;
	return e;
}

/*出列*/
int DeQueue(Queue Q){
	if (Q->front == Q->rear)			
		return NULL;
	int e = Q->data[Q->front];				
	Q->front = (Q->front + 1) % MAXSIZE;	
	return e;
}

void main(){
	Queue Q;
	Q = InitQueue();

	printf("入列: \n");
	for (int i = 1; i <= 10; i++){
		printf(" %d",EnQueue(Q, i));
	}
	QueueEmpty(Q);
	printf("队列长度为:%d\n", QueueLength(Q));
	printf("队列头元素为:%d\n", GetHead(Q));

	printf("\n");

	printf("出列: \n");
	for (int i = 1; i <= 5; i++){
		printf("%d ",DeQueue(Q, i));
	}
	QueueEmpty(Q);
	printf("队列长度为:%d\n", QueueLength(Q));
	printf("队列头元素为:%d\n", GetHead(Q));
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值