数据结构——顺序队列的基本操作(C语言实现)

1、定义

#define QUEUE_DEFAULT_SIZE 8
typedef struct SeqQueue
{
	ElemType *base;
	int capacity;
	int front;
	int rear;
}SeqQueue;

2、初始化

void SeqQueueInit(SeqQueue* psq)
{
	assert(psq != NULL);
	psq->capacity = QUEUE_DEFAULT_SIZE;
	psq->base = (ElemType*)malloc(sizeof(ElemType)*psq->capacity);
	psq->front = psq->rear = 0;
}

3、判空

bool SeqQueueEmpty(SeqQueue *psq)
{
	assert(psq != NULL);
	return psq->front == psq->rear;
}

4、入队、出队

void SeqQueueEn(SeqQueue* psq, ElemType x)
{
	assert(psq != NULL);
	if (psq->rear >= psq->capacity)
	{
		printf("队列已满,%d不能入队!\n");
		return;
	}
	psq->base[psq->rear++] = x;
}
void SeqQueueDe(SeqQueue* psq)
{
	assert(psq != NULL);
	if (SeqQueueEmpty(psq))
	{
		printf("队列已空,不能出队!\n");
		return;
	}
	psq->front++;
}

5、打印

void SeqQueueShow(SeqQueue* psq)
{
	assert(psq != NULL);
	for (int i = psq->front; i < psq->rear; i++)
	{
		printf("%d ", psq->base[i]);
	}
	printf("\n");
}

6、取头元素

ElemType SeqQueueFront(SeqQueue* psq)
{
	assert(psq != NULL);
	assert(!SeqQueueEmpty(psq));
	return psq->base[psq->front];
}

7、求队列元素个数

int SeqQueueSize(SeqQueue *psq)
{
	assert(psq != NULL);
	return (psq->rear - psq->front);
}

8、摧毁队列

void SeqQueueDestroy(SeqQueue *psq)
{
	assert(psq != NULL);
	free(psq->base);
	psq->base = NULL;
	psq->capacity = psq->front = psq->rear = 0;
}

 

你可能感兴趣的:(数据结构——顺序队列的基本操作(C语言实现))