#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;
}
(数据结构)(C++)链队的建立和部分基本操作
于 2023-07-08 22:53:54 首次发布