链队列 ——以c语言为例

//链队列
#include <stdio.h>
#include <iostream>
using namespace std;
#define qElemType int
typedef struct qNode{
	qElemType data;
	qNode *next;
}*qPtr;
typedef struct queue{
	qPtr front;
	qPtr rear;
}; 
//初始化队列;front,rear指针都指向头结点 
void initQueue(queue &Q){
	Q.front=Q.rear=new qNode;
}
//判空:返回1表示空队列,返回0,则不是空队列
int isEmpty(queue Q){
	return Q.front==Q.rear;
}
//插入元素到队列
void enQueue(queue &Q,qElemType e){
	qPtr newNode =new qNode;
	newNode->data=e;
	Q.rear->next=newNode;
	Q.rear=newNode;
}
//在队列中删除元素
void deQueue(queue &Q,qElemType &e){
	if(isEmpty(Q)){
		cout<<"队列为空"<<endl;
		return;
	}
	//保存被删元素
	e=Q.front->next->data;
	//保存被删元素指针
	qPtr temp=Q.front->next;
	Q.front->next=Q.front->next->next;
	//删除被删元素指针
	delete temp;
	
}
//打印队列中的元素
void printFrontAndRear(queue Q){
	cout<<"队列的第一个元素为:";
	cout<<Q.front->next->data<<endl;
	cout<<"队列的最后一个元素为:";
	cout<<Q.rear->data<<endl;
}
int main(){
	queue 	Q;
	initQueue(Q);
	enQueue(Q,1);
	enQueue(Q,2);
	enQueue(Q,3);
	enQueue(Q,4);
	enQueue(Q,5);
	printFrontAndRear(Q);
	qElemType val;
	deQueue(Q,val);
	cout<<"队列中被删除的元素为:"<<val<<endl;
	printFrontAndRear(Q);
	
}
在这里插入代码片

运行结果截图:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值