数据结构-链式队列实现

头文件Queue.h

#include<stdio.h>
#include<stdbool.h>
#include<malloc.h>
#include<assert.h>
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) {
	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));
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值