数据结构---队列的链式实现

本文主要探讨数据结构中的队列,并侧重于队列的链式实现方法。作者提到,理解了数据结构的基本概念后,其各种操作和实现会变得相对简单。然而,由于错过了两次关于串和数组的课程,作者对于这部分内容感到困惑,担心在即将到来的数据结构期中考试中会遇到困难。
摘要由CSDN通过智能技术生成

其实理解了一个数据结构后,它的各种实现与操作就能很容易的写出来 话说貌似下周数据结构有期中考试...Orz我翘了两次课 串和数组那地方还不太懂 要跪啊....

#include <stdio.h>
#include <stdlib.h>

typedef int ElemType;

typedef struct Node
{
	ElemType Data;
	struct Node *Next;
}Node, *PtrNode;

typedef struct Queue
{
	PtrNode Front;
	PtrNode Rear;
}Queue, *LinkQueue;


//create an empty linkqueue
LinkQueue InitQueue();

//destroy linkqueue
void DestroyQueue(LinkQueue Q);

//clear a linkqueue
void ClearQueue(LinkQueue Q);

//if the linkqueue is empty return 1
int IsEmpty(LinkQueue Q);

//get the length of linkqueue
int QueueLength(LinkQueue Q);

//get the head of linkqueue
ElemType GetHead(LinkQueue Q);

//insert an element to the rear of linkqueue
void EnQueue(LinkQueue Q, ElemType E);

//get and delete the front of linkqueue
ElemType DeQueue(LinkQueue Q);

void PrintQueue(LinkQueue Q);

int main()
{
	LinkQueue Q = InitQueue();
	EnQueue(Q, 1);
	EnQueue(Q, 2);
	EnQueue(Q, 3);
	EnQueue(Q, 4);
	PrintQueue(Q);
	printf("%d\n", GetHead(Q));
	printf("%d\n", QueueLength(Q));
	DeQueue(Q);
	DeQueue(Q);
	PrintQueue(Q);
	DestroyQueue(Q);
	return 0;
}


LinkQueue InitQueue()
{
	LinkQueue Q = (LinkQueue)malloc(sizeof(Queue));
	Q->Front = Q->Rear = (PtrNode)malloc(sizeof(Node));
	Q->Front->Next = NULL;
	return Q;
}

void DestroyQueue(LinkQueue Q)
{
	while(Q->Front)
	{
		Q->Rear = Q->Front->Next;
		free(Q->Front);
		Q->Front = Q->Rear;
	}
}

void ClearQueue(LinkQueue Q)
{
	Q->Rear = Q->Front;
	PtrNode Tmp = Q->Front->Next;
	while(Tmp)
	{
		Q->Front = Tmp->Next;
		free(Tmp);
		Tmp = Q->Front;
	}
	Q->Front = Q->Rear;
}

int IsEmpty(LinkQueue Q)
{
	return (Q->Front == Q->Rear) ? 1 : 0;
}

int QueueLength(LinkQueue Q)
{
	int count = 0;
	PtrNode Tmp = Q->Front;
	while(Tmp != Q->Rear)
	{
		Tmp = Tmp->Next;
		count ++;
	}
	return count;
}

ElemType GetHead(LinkQueue Q)
{
	return Q->Front->Next->Data;
}

void EnQueue(LinkQueue Q, ElemType E)
{
	PtrNode Tmp = (PtrNode)malloc(sizeof(Node));
	Tmp->Data = E;
	Tmp->Next;
	Q->Rear->Next = Tmp;
	Q->Rear = Tmp;
}

ElemType DeQueue(LinkQueue Q)
{
	PtrNode Tmp = Q->Front->Next;
	ElemType Data = Tmp->Data;
	Q->Front->Next = Tmp->Next;
	free(Tmp);
	return Data;
}

void PrintQueue(LinkQueue Q)
{
	PtrNode Tmp = Q->Front->Next;
	while(Tmp)
	{
		printf("%d ", Tmp->Data);
		Tmp = Tmp->Next;
	}
	printf("\n");
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值