队列模拟实现

头文件

#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
struct BinaryTreeNode;
typedef struct BinaryTreeNode* QDataType;
typedef struct QListNode // 队节点
{
	struct QListNode* _next;
	QDataType _data;
}QNode;

// 队列的结构 
typedef struct Queue
{
	QNode* _front;//头指针 出
	QNode* _rear;//尾指针  入
}Queue;

// 初始化队列 
void QueueInit(Queue* q);
// 队尾入队列 
void QueuePush(Queue* q, QDataType data);
// 队头出队列 
void QueuePop(Queue* q);
// 获取队列头部元素 
QDataType QueueFront(Queue* q);
// 获取队列队尾元素 
QDataType QueueBack(Queue* q);
// 获取队列中有效元素个数 
int QueueSize(Queue* q);
// 检测队列是否为空,如果为空返回非零结果,如果非空返回0 
int QueueEmpty(Queue* q);
// 销毁队列 
void QueueDestroy(Queue* q);
void PrintQueue(Queue* q);

接口实现

void QueueInit(Queue* q) {
	q->_front = q->_rear = NULL;
}
void QueuePush(Queue* q, QDataType data) {
	QNode* Newnode = (QNode*)malloc(sizeof(QNode));
	if (Newnode == NULL) {
		printf("Create Fail!\n");
		exit(-1);
	}
	Newnode->_data = data;
	Newnode->_next = NULL;
	if (q->_front == NULL) {
		q->_front = Newnode;
		q->_rear = Newnode;//只有一个节点单独处理
	}
	else {
		q->_rear->_next = Newnode;//尾指针向后移动
		q->_rear = Newnode;
	}
}
void QueuePop(Queue* q) {
	assert(q);
	assert(q->_front);
	QNode* head_next = q->_front->_next;
	free(q->_front);
	q->_front = head_next;
	if (head_next == NULL) {
		q->_rear = NULL;
	}
}
QDataType QueueFront(Queue* q) {
	assert(q);
	assert(q->_front);
	return q->_front->_data;
}
QDataType QueueBack(Queue* q) {
	assert(q);
	assert(q->_rear);
	return q->_rear->_data;
}
int QueueSize(Queue* q) {
	assert(q);
	if (q->_front == NULL) {
		return 0;
	}
	QNode* cur = q->_front;
	int count = 1;
	while (cur != q->_rear) {
		cur = cur->_next;
		count++;
	}
	return count;
}
int QueueEmpty(Queue* q) {
	assert(q);
	return q->_front == NULL ? 1 : 0;
}
void QueueDestroy(Queue* q) {
	assert(q);
	QNode* cur = q->_front;
	while (cur != NULL) {
		QNode* next = cur->_next;
		free(cur);
		cur = next;
	}
	q->_front = q->_rear = NULL;
}
void PrintQueue(Queue* q) {
	QNode* cur = q->_front;
	while (cur != NULL) {
		printf("%d  ", cur->_data);
		cur = cur->_next;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值