C语言-队列-顺序结构(数组实现)

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

// 数组去模拟栈队列的顺序存储
#define MAX_SIZE 1024

//顺序队列结构体
typedef struct SEQQUEUE {
	void *data[MAX_SIZE];
	int size;
}SeqQueue;

//初始化栈
SeqQueue* Init_SeqQueue() {
	SeqQueue *queue = (SeqQueue*)malloc(sizeof(SeqQueue));
	for (int i = 0; i < MAX_SIZE; i++)
	{
		queue->data[i] = NULL;
	}
	queue->size = 0;
	return queue;
}

// 入队
void Push_SeqQueue(SeqQueue* queue, void* data) {
	//数组左边当队头
	if (queue == NULL) {
		return;
	}
	if (queue->size == MAX_SIZE) {
		return;
	}
	if (data == NULL) {
		return;
	}
	queue->data[queue->size] = data;
	queue->size++;
}

//出队
void* Pop_SeqQueue(SeqQueue* queue) {
	if (queue == NULL) {
		return NULL;
	}
	if (queue->size == 0) {
		return NULL;
	}
	void *top = queue->data[0];

	for (int i = 0; i < queue->size - 1; i++) {
		queue->data[i] = queue->data[i + 1];
	}
	queue->size--;

	return top;
}

//返回队尾元素
void* Back_SeqQueue(SeqQueue* queue) {
	if (queue == NULL) {
		return NULL;
	}
	if (queue->size == 0) {
		return NULL;
	}
	return queue->data[queue->size - 1];
}

//判断是否为空
int IsEmpty(SeqQueue* queue) {
	if (queue == NULL) {
		return -1;
	}
	if (queue->size == 0) {
		return 1;
	}
	return 0;
}

//返回队列中元素个数
int Size_SeqQueue(SeqQueue* queue) {
	if (queue == NULL) {
		return -1;
	}
	return queue->size;
}

//清空栈
void Clear_SeqQueue(SeqQueue* queue) {
	if (queue == NULL) {
		return;
	}
	for (int i = 0; i < queue->size; i++) {
		queue->data[i] = NULL;
	}
	queue->size = 0;
}

//销毁
void FreeSpace_SeqQueue(SeqQueue* queue) {
	if (queue == NULL) {
		return;
	}
	free(queue);
}

typedef struct PERSON {
	char name[64];
	int age;
}Person;

int main(void) {

	//创建队列
	SeqQueue *queue = Init_SeqQueue();
	//创建数据
	Person p1 = { "aaa",10 };
	Person p2 = { "bbb",20 };
	Person p3 = { "ccc",30 };
	Person p4 = { "ddd",40 };
	Person p5 = { "eee",50 };
	//入队
	Push_SeqQueue(queue, &p1);
	Push_SeqQueue(queue, &p2);
	Push_SeqQueue(queue, &p3);
	Push_SeqQueue(queue, &p4);
	Push_SeqQueue(queue, &p5);

	//输出队尾元素
	Person *backPerson = (Person*)Back_SeqQueue(queue);
	printf("Name:%s Age:%d\n", backPerson->name, backPerson->age);

	//输出
	while (Size_SeqQueue(queue) > 0) {
		//访问队头
		Person* person = (Person*)Pop_SeqQueue(queue);
		printf("Name:%s Age:%d\n", person->name, person->age);
	}

	//释放内存
	FreeSpace_SeqQueue(queue);

	system("pause");
	return 0;
}

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页