栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

数据结构——链式队列

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构——链式队列

链式队列
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#include
#include
#include
#include 
using namespace std;

//函数结果状态代码
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define TRUE 1
#define FALSE 0

#define QUEUE_INIT_SIZE 100


typedef int ElemType;
typedef int Status;


typedef struct QNode {
	ElemType data;
	QNode* next;
}QNode, * QueuePtr;

typedef struct {
	QueuePtr front;//链队的首地址
	QueuePtr rear;//链队列的尾地址
}linkQueue;

//构造一个空队列
Status InitlinkQueue(linkQueue* Q)
{
	//创建QNode
	Q->front = Q->rear = (QueuePtr)malloc(sizeof(QNode));
	if (!Q->front) return ERROR;
	//头结点的next置空
	Q->front->next = NULL;
	return OK;
}
//销毁队列Q,Q不存在
Status DestoryQuqeue(linkQueue* Q)
{
	while (Q->front)
	{
		Q->rear = Q->front->next;
		free(Q->front);
		Q->front = Q->rear;
	}
	return OK;
}

//计算Queue的长度
int  QueueLength(linkQueue* Q)
{
	QueuePtr q = Q->front->next;
	int length = 0;
	while (q)
	{
		q = q->next;
		length++;
	}
	return length;

}

//判断链队列是否为空
Status QueueEmpty(linkQueue* Q)
{
	if (Q->front==Q->rear) return TRUE;
	return FALSE;
}

//入队操作
Status EnQueue(linkQueue* Q, ElemType e)
{
	QueuePtr node = (QueuePtr)malloc(sizeof(QNode));
	if (!node) exit(OVERFLOW);
	node->data = e;
	node->next = NULL;
	//接入链队列中
	Q->rear->next = node;
	Q->rear = node;
	return OK;
}

//出队操作
Status DeQueue(linkQueue* Q, ElemType* e)
{
	if (Q->front == Q->rear) return ERROR;
	QNode* q = Q->front->next;
	*e = q->data;
	//链接
	Q->front->next = q->next;
	//为最后一个结点
	if (q == Q->rear)Q->rear = Q->front;
	free(q);
	cout << "Dequeue:" << *e << endl;
	return OK;
}
//遍历
void DisPlayQueue(linkQueue Q)
{
	if (QueueEmpty(&Q)==1) {
		cout << "link Queue 为空" << endl;
		return ;
	}
	QNode* q = Q.front->next;
	cout << "Queue:"<data << " ";
		q = q->next;
	}
	cout << endl;
}
int main()
{
	linkQueue q;//结构体
	cout << "InitlinkQueue:" << InitlinkQueue(&q) << endl;
	cout << "Queue length:" << QueueLength(&q) << endl;
	cout << "Queue is Empty:" << QueueEmpty(&q) << endl;
	EnQueue(&q, 1);
	EnQueue(&q, 2);
	EnQueue(&q, 3);
	EnQueue(&q, 4);
	EnQueue(&q, 5);
	EnQueue(&q, 6);
	ElemType e;
	DeQueue(&q, &e);
	DeQueue(&q, &e);
	DeQueue(&q, &e);
	cout << "Queue length:" << QueueLength(&q) << endl;
	DisPlayQueue(q);
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/783794.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号