(数据结构)(C++)链队的建立和部分基本操作

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
 
using namespace std;
 
#define  ElemType int

#define MAXSIZE 4
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -1

typedef struct qnode{
	ElemType data;
	struct qnode *next; 
}Dnode,*DataNode;//链队数据结点类型 

typedef struct{
	DataNode front;
	DataNode rear;
}Lqueue,*LinkQueue;//链队数据类型 

//初始化 
void InitQueue(LinkQueue &q){
	q=new Lqueue;
	q->front=q->rear=NULL; 
}

//销毁
void DestroyQueue(LinkQueue &q){
	DataNode pre=q->front;//头结点
	DataNode p; 
	if(pre!=NULL){
		p=pre->next;
		while(p!=NULL){
			delete pre;
			pre=p;p=p->next;
		}
		delete p;
	}
	delete q;
} 

//判断是否为空 
bool QueueEmpty(LinkQueue q){
	return (q->rear==NULL);
} 

//进队(尾插法) 
bool InputQueue(LinkQueue &q){
	 cout<<"请输入你要入队的元素个数:";
	    int number;
	    cin>>number;
	   int i;
	for(i=0;i<number;i++){
	    	DataNode p;
	        p=new Dnode;
	        p->next=NULL;
		cout<<"请输入第"<<i+1<<"个元素:";
		ElemType elem;
		cin>>elem;
		p->data=elem;
		if(q->rear==NULL){
			q->front=p;
			q->rear=p;
		} else{
			q->rear->next=p;
			q->rear=q->rear->next;
		}
	} 
} 

//出队
bool OutputQueue(LinkQueue &q){
	DataNode t; 
	if(q->rear==NULL){
		cout<<"队列为空!";
		cout<<endl;
		return false;
	} 
	t=q->front;
	if(q->front==q->rear)//原队列只有一个数据结点的时候
	{
		q->front=q->rear=NULL; 
	 }else{
	 	q->front=q->front->next; 
	 }
	 ElemType elem;
	 elem=t->data;
	 cout<<"元素"<<elem<<"出队。"; 
	 cout<<endl;
	 delete t;
	 return true; 
} 


int main(){
	LinkQueue q; 
	InitQueue(q);
	
	InputQueue(q);
	cout<<endl;
	
	bool flag=QueueEmpty(q);
	if(flag){
		cout<<"此队列为空。"<<endl; 
	}else{
		cout<<"此队列非空。"<<endl;
	}
	cout<<endl; 
	
	while(OutputQueue(q)){
		OutputQueue(q);
	}
	cout<<endl;
	
	QueueEmpty(q); 
	cout<<endl;
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值