#include<iostream>
#include<stdlib.h>
typedef int ElemType;
using namespace std;
#define MaxSize 50
typedef struct LinkNode{
ElemType data;
struct LinkNode* next;
}LinkNode;
typedef struct{
LinkNode* front,*rear;
}LinkQueue;
//初始化
void InitQueue(LinkQueue &Q)
{
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.front->next = NULL;
}
//判断队空
bool isEmpty(LinkQueue Q)
{
if(Q.front==Q.rear)
return true;
else
return false;
}
//入队(链队列不用考虑队满)
void EnQueue(LinkQueue &Q,ElemType x)
{
LinkNode *s=(LinkNode*)malloc(sizeof(LinkNode));
s->data=x;
s->next=NULL;
Q.rear->next=s;
Q.rear=s;
}
//出队
bool DeQueue(LinkQueue &Q,ElemType &x)
{
//空队列
if(Q.rear==Q.front)
{
return false;
}
LinkNode *p=Q.front->next;
x=p->data;
Q.front->next=p->next;
if(Q.rear==p)
{
Q.rear=Q.front;
}
free(p);
return true;
}
int main()
{
LinkQueue hahaha;
InitQueue(hahaha);
if(isEmpty(hahaha))
{
cout<<"this queue is empty"<<endl;
}
//验证入队
for(int i=0;i<5;i++)
{
EnQueue(hahaha,i);
}
if(isEmpty(hahaha))
{
cout<<"this queue is empty"<<endl;
}
else
{
cout<<"this queue is not empty"<<endl;
}
LinkNode* temp = hahaha.front->next;//temp指向hahaha的队头指针
while(temp)
{
cout<<temp->data<<endl;//输出temp当前所指的节点的数据域
temp = temp->next;//temp向后循环
}
//验证出队
for(int i=0;i<5;i++)
{
int x;
DeQueue(hahaha,x);
temp = hahaha.front->next;//temp指向hahaha的队头指针
while(temp)
{
cout<<temp->data<<" ";//输出temp当前所指的节点的数据域
temp = temp->next;//temp向后循环
}
cout<<endl;
}
if(isEmpty(hahaha))
{
cout<<"this queue is empty"<<endl;
}
else
{
cout<<"this queue is not empty"<<endl;
}
}
![](https://img-blog.csdnimg.cn/direct/471c9102b16b4af1bed8c46aca974175.png)