用链表表示的队列简称为链队列。
一个链队列显然需要分别指示队头和队尾的两个指针。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef struct node
{
int data;
struct node *next;
} Node,*LinkQueue;//链队结点的类型及指针
typedef struct NODE
{
LinkQueue front;
LinkQueue rear;
}*LinkList;//将头尾指针封装在一起的链队
LinkList InitQueue()//创建链队列
{
LinkList H;
H->rear=(LinkQueue)malloc(sizeof(Node));
H->front=H->rear;
H->front->next=NULL;
return H;
}
LinkList DestoryQueue(LinkList H)//摧毁队列
{
while(H->front)
{
H->rear=H->front->next;
free(H->front);
H->front=H->rear;
}
return H;
}
void deleteEle(LinkList H,int &e)//删除队列元素
{
LinkQueue p;
p=H->front->next;
e=p->data;
H->front->next=p->next;
if(H->rear==p) H->rear=H->front;
free(p);
}
void EnQueue(LinkList H,int e)//添加队列元素
{
LinkQueue p=(LinkQueue)malloc(sizeof(Node));
p->data=e;
p->next=NULL;
H->rear->next=p;
H->rear=p;
}
void printQueue(LinkList H)//输出队列元素
{
LinkQueue L=H->front->next;
while(L!=NULL)
{
cout<<L->data<<" ";
L=L->next;
}
cout<<endl;
}
int getTop(LinkList H)//取队列头元素
{
return H->front->next->data;
}