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

数据结构-链式队列实现

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

数据结构-链式队列实现

头文件Queue.h

#include
#include
#include
#include
typedef int ElemType;
typedef struct QueueNode {
	ElemType data;
	struct QueueNode *next;
}QueueNode;
typedef struct LinkQueue {
	QueueNode *front;
	QueueNode *tail;
}LinkQueue;

void InitQueue(LinkQueue *Q);
void EnQueue(LinkQueue *Q,ElemType x);
void DeQueue(LinkQueue *Q);
bool IsEmptyQueue(LinkQueue *Q);
void ShowQueue(LinkQueue *Q);
void GetHead(LinkQueue *Q, ElemType *v);
ElemType Length(LinkQueue *Q);
void Clear(LinkQueue *Q);
void Destroy(LinkQueue *Q);

函数实现Queue.c

#include"Queue.h"
void InitQueue(LinkQueue *Q) {
	QueueNode *s = (QueueNode*)malloc(sizeof(QueueNode));
	assert(s != NULL);
	Q->front = Q->tail = s;
	Q->tail->next = NULL;
}

bool IsEmptyQueue(LinkQueue *Q) {
	return Q->front == Q->tail;
}

void EnQueue(LinkQueue *Q, ElemType x) {
	QueueNode *s = (QueueNode*)malloc(sizeof(QueueNode));
	assert(s != NULL);
	s->data = x;
	s->next = NULL;
	Q->tail->next = s;
	Q->tail = s;
}

void DeQueue(LinkQueue *Q, ElemType x) {
	if (Q->front == Q->tail)
		return;
	QueueNode *p = Q->front->next;
		Q->front->next = p->next;
		free(p);
		if (p == Q->tail)
			Q->tail = Q->front;
	}

void ShowQueue(LinkQueue *Q) {
	QueueNode *p = Q->front->next;
	printf("Front:>");
	while (p != NULL) {
		printf("%d ", p->data);
		p = p->next;
	}
	printf("<:Tail");
}

void GetHead(LinkQueue *Q, ElemType *v) {
	if (Q->front == Q->tail)
		return;
	QueueNode *p = Q->front->next;
	*v = p->data;
}

ElemType Length(LinkQueue *Q) {
	int len = 0;
	QueueNode *p = Q->front->next;
	while (p != NULL) {
		len++;
		p = p->next;
	}
	return len;
}

void Clear(LinkQueue *Q) {
	QueueNode *p = Q->front->next;
	if (Q->front == Q->tail)
		return;
	while (p != NULL) {
		Q->front->next = p->next;
		free(p);
		p = Q->front->next;
	}
	Q->tail = Q->front;
}

void Destroy(LinkQueue *Q) {
	Clear(Q);
	free(Q->front);
	Q->front = Q->tail = NULL;
}

测试函数Main.c

#include"Queue.h"
int main() {
	LinkQueue Q;
	InitQueue(&Q);
	for (int i = 1; i <= 10; ++i) {
		EnQueue(&Q,i);
	}
	ShowQueue(&Q);
	printf("n");
	DeQueue(&Q);
	ShowQueue(&Q);
	printf("n");
	printf("len=%d", Length(&Q));
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/869004.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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