数据结构——链队列的基本操作

InitQueue(&Q): 初始化队列Q

QueueEmpty(): 判断队列是否为空

EnQueue(e): 将元素e放入队尾

DeQueue(e): 移走队头元素,由e带回该元素的值

GetFront(): 获取队头元素的值,但不从队列中移走该元素

Length(): 计算并返回队列中元素的个数

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

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

typedef struct{
	QueuePtr front;
    QueuePtr rear;
}LinkQueue;

bool InitQueue(LinkQueue &Q){
	Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
	if(!Q.front)
		return false;
	Q.front->next = NULL;
	return true;
}

bool QueueEmpty(LinkQueue &Q){
	if(Q.front == Q.rear)
		return true;
	else
		return false;
}

bool EnQueue(LinkQueue &Q,int e){
	QueuePtr p;
	p = (QueuePtr)malloc(sizeof(QNode));
	if(!p)
		return false;
	p->data = e;
	Q.rear->next = p;
	Q.rear = p;
	Q.rear->next = NULL;
	return true;
}

int GetFront(LinkQueue &Q){
	return Q.front->next->data;
}
int Length(LinkQueue &Q){
	int count = 0;
	QueuePtr  p= Q.front;
	while(p != Q.rear){
		count++;
		p = p->next;
	}
	return count;
}

int DeQueue(LinkQueue &Q){
	QNode *p;
	p = Q.front->next;
	int e = p->data;
	Q.front->next = p->next;
	free(p); 
	return e;
}

int main(){
	LinkQueue Q;int e;
	InitQueue(Q);
	if(QueueEmpty(Q))
		printf("链队列为空!\n");
	else
		printf("链队列不为空!\n");
	for(int i=0;i<5;i++){
		printf("请输入第%d个数据:",1+i);
		scanf("%d",&e);
		EnQueue(Q,e);
	}
	if(QueueEmpty(Q))
		printf("链队列为空!\n");
	else
		printf("链队列不为空!\n");
	printf("队头元素:%d\n",GetFront(Q));
	printf("元素个数:%d\n",Length(Q));
	printf("已删除队头元素:%d\n",DeQueue(Q));
	printf("队头元素:%d\n",GetFront(Q));
	printf("元素个数:%d\n",Length(Q));
	return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

末世灯光

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值