队列的基本接口

Queue.h

#ifndef _SQ_H_
#define _SQ_H_

#include<stdio.h>
#include<Windows.h>

#define MAXSIZE 100

typedef int QuDataType;

typedef struct Queue
{
	QuDataType data[MAXSIZE];
	QuDataType * front;
	QuDataType * rear;
	size_t size;
}Queue;

void QueueInit(Queue* pq);
void QueueDestory(Queue* pq);

void QueuePush(Queue* pq, QuDataType x);
void QueuePop(Queue* pq);

QuDataType QueueFront(Queue* pq);
QuDataType QueueBack(Queue* pq);
int QueueEmpty(Queue* pq);
int QueueSize(Queue* pq);

#endif /*_SQ_H_*/

Queue.c

#include"Queue.h"

void QueueInit(Queue* pq)
{
	pq->front = pq->data;
	pq->rear = pq->data;
	pq->size = 0;
}

void QueueDestory(Queue* pq)
{
	pq->front = pq->data;
	pq->rear = pq->data;
	pq->size = 0;
}

void QueuePush(Queue* pq, QuDataType x)
{
	//判满
	if (pq->size + 1 == MAXSIZE)
	{
		return;
	}
	/*若无pq->size,判满条件也可以为:
	if (pq->rear + 1 - MAXSIZE == pq->data && pq->data == pq->front
		|| pq->rear + 1 == pq->front)
	{
		return ;
	}
	*/

	*(pq->rear) = x;
	pq->rear++;

	pq->size++;

	if (pq->rear - pq->data == MAXSIZE)
	{
		pq->rear = pq->data;
	}
	

}

void QueuePop(Queue* pq)
{
	//判空
	if (pq->size == 0)
	{
		return;
	}
	pq->front++;

	pq->size--;

	if (pq->front - pq->data == MAXSIZE)
	{
		pq->front = pq->data;
	}

}

QuDataType QueueFront(Queue* pq)
{
	if (pq->size == 0)
	{
		return -1;
	}
	return *(pq->front);
}


QuDataType QueueBack(Queue* pq)
{
	if (pq->size == 0)
	{
		return -1;
	}
	if (pq->rear == pq->data)
	{
		return pq->data[MAXSIZE - 1];
	}
	return *(pq->rear - 1);
}

main.c

#include "Queue.h"

int main()
{
	Queue qu;

	QueueInit(&qu);
	QueuePush(&qu, 3);
	QueuePush(&qu, 5);
	QueuePush(&qu, 8);
	QueuePush(&qu, 7);
	printf("%d ", QueueFront(&qu));
	QueuePop(&qu);
	printf("%d ", QueueFront(&qu));
	QueuePop(&qu);
	QueuePush(&qu, 9);
	QueuePush(&qu, 10);
	printf("%d ", QueueFront(&qu));
	QueuePop(&qu);
	printf("%d ", QueueFront(&qu));
	QueuePop(&qu);

	QueuePush(&qu, 12);
	QueuePush(&qu, 13);


	printf("%d ", QueueFront(&qu));
	QueuePop(&qu);
	printf("%d ", QueueFront(&qu));
	QueuePop(&qu);
	printf("%d ", QueueFront(&qu));
	QueuePop(&qu);
	printf("%d ", QueueFront(&qu));
	QueuePop(&qu);

	QueueDestory(&qu);
	system("pause");
	return 0;
}

THE END

发布了67 篇原创文章 · 获赞 15 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_43746320/article/details/96998674