c链队

#include <iostream>
#include <malloc.h>
using namespace std;

//声明链队数据结点类型
typedef struct dNode {
	char data;
	struct dNode* next;
}dataNode;

//声明链队类型
typedef struct {
	dataNode* front;
	dataNode* rear;
}linkQuNode;

//初始化链队
void InitQueue(linkQuNode*& q) {
	q = (linkQuNode*)malloc(sizeof(linkQuNode));
	q->front = q->rear = NULL;
}
//判断链队是否为空
bool EmptyQueue(linkQuNode* q) {
	return(q->rear == NULL);
}
//进队操作
bool EnterQueue(linkQuNode*& q, char c) {
	dataNode* s = NULL;
	s = (dataNode*)malloc(sizeof(dataNode));
	s->data = c;
	s->next = NULL;
	if (q->rear == NULL)//如果链队为空,则新结点即是首结点,又是尾结点
	{
		q->front = q->rear = s;
	}
	else {				//将s结点链到队尾,并将rear指向他
		q->rear->next = s;
		q->rear = s;
	}
	return true;
}
//出队操作
bool OutQueue(linkQuNode*& q, char &c) {
	dataNode* p = NULL;
	//如果链队为空
	if (q->rear == NULL)
	{
		return false;
	}
	p = q->front;//p指向第一个数据节点
	if (q->front == q->rear)//队列中只有一个节点时
	{
		q->front = q->rear = NULL;
	}
	else//队列中有多个结点时
	{
		q->front = q->front->next;
	}
	c = p->data;
	free(p);
	return true;
}
//销毁队列
void DestroyQueue(linkQuNode*& q) {
	dataNode* pre = q->front, * p = NULL;
	if (pre!=NULL)//如果q->front为空,代表只有一个头结点,此时直接释放头结点
	{
		p = pre->next;
		while (p!= NULL)
		{
			free(pre);
			pre = p;
			p = p->next;
		}
		free(pre);
	}
	free(q);
}

int main() {
	linkQuNode* q;
	char c = '\0';
	InitQueue(q);
	cout << (EmptyQueue(q) ? "空" : "非空") << endl;
	EnterQueue(q, 'a');
	EnterQueue(q, 'b');
	EnterQueue(q, 'c');
	EnterQueue(q, 'd');
	EnterQueue(q, 'e');
	cout << (EmptyQueue(q) ? "空" : "非空") << endl;
	//出队列
	if (OutQueue(q, c)) {
		cout << c << endl;
	}
	if (OutQueue(q, c)) {
		cout << c << endl;
	}
	if (OutQueue(q, c)) {
		cout << c << endl;
	}
	if (OutQueue(q, c)) {
		cout << c << endl;
	}
	if (OutQueue(q, c)) {
		cout << c << endl;
	}
	cout << (EmptyQueue(q) ? "空" : "非空") << endl;
	DestroyQueue(q);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值