队的实现

队:一种头删尾插的数据结构
//头文件

#include<stdio.h>
#include<malloc.h>
#include<assert.h>
typedef int QUDataType;
typedef struct QueueNode { 
	struct QueueNode* _next;    
	QUDataType _data; 
}QueueNode;
typedef struct Queue {
	QueueNode* _front; // 队头    
	QueueNode* _rear;  // 队尾
}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);
//测试函数
void TestQueue();
//输出函数
void print_quene();


//c文件

#include"queue.h"
void QueueInit(Queue* pq) {
	assert(pq);
	pq->_front = NULL;
	pq->_rear = NULL;
}
void QueueDestory(Queue* pq) {
	assert(pq);
	while (pq->_front) {
		free(pq->_front);
	}
	pq->_front = NULL;
	pq->_rear = NULL;
}
void QueuePush(Queue* pq, QUDataType x) {
	assert(pq);
	QueueNode* node = (QueueNode*)malloc(sizeof(QueueNode));
	node->_data = x;
	node->_next = NULL;
	if (pq->_front ==NULL){
		pq->_front = node;
		pq->_rear = node;
		pq->_front->_next=NULL;
	}else{
		pq->_rear->_next = node;
		pq->_rear = pq->_rear->_next;
	}
}
void QueuePop(Queue* pq) {
	assert(pq);
	if (pq->_front == NULL) {
		return;
	}
	pq->_front = pq->_front->_next;
	if (pq->_front == NULL) {
		pq->_rear = NULL;
	}
}
QUDataType QueueFront(Queue* pq) {
	assert(pq);
	if (pq->_front == pq->_rear == NULL) {
		return NULL;
	}
	return pq->_front->_data;
}
QUDataType QueueBack(Queue* pq) {
	assert(pq);
	if (pq->_front == pq->_rear == NULL) {
		return NULL;
	}
	return pq->_rear->_data;
}
int QueueEmpty(Queue* pq) {
	assert(pq);
	if (pq->_front == pq->_rear == NULL) {
		return 1;
	}
	return 0;
}
int QueueSize(Queue* pq) {
	assert(pq);
	Queue* tmp = pq;
	int size = 0;
	while (tmp->_front) {
		size++;
		tmp->_front = tmp->_front->_next;
	}
	return size;
}
void print_quene(Queue* pq) {
	assert(pq);
	if (pq->_front == NULL) {
		return;
	}
	QueueNode* tmp = pq->_front;
	while (tmp) {
		printf("%d ",tmp->_data);
		tmp = tmp->_next;
	}
	printf("\n");
}
void TestQueue(){
	Queue pq;
    QueueInit(&pq);
	QueuePush(&pq, 0);
	QueuePush(&pq, 1);
	QueuePush(&pq, 2);
	QueuePush(&pq, 3);
	print_quene(&pq);
	QueuePop(&pq);
	QueuePop(&pq);
	print_quene(&pq);
	QueuePop(&pq);
	print_quene(&pq);
	QueuePop(&pq);
	print_quene(&pq);
}

int main() {
	TestQueue();
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值