链队
链队就是采用链式存储结构存储队列,链队的特点就是不存在队满上溢的情况。
链队的要素
- 队空状态
lqu->rear==NULL或者lqu->front==NULL
- 队满状态:不存在队满的情况(假设内存无限大的情况不存在)。
- 元素进队操作(假设p指向进队元素)
lqu->rear->next=p;
lqu->rear=p;
- 元素出队操作(假设x存储出队元素)
p=lqu->front;
lqu->front=p->next;
x=p->data;
free(p);
链队列的定义
(1)队结点类型定义
typedef struct QNode
{
int data;//数据域
struct QNode *next;//指针域
}QNode;//队结点类型定义
(2)链队类型定义
typedef struct
{
QNode *front;//队头指针
QNode *rear;//队尾指针
}LiQueue;
init.h
#ifndef _INIT_H
#define _INIT_H
#define TRUE 1
#define FASLE 0
#define OK 1
#define ERROR -1
#define OVERFLOW -2
typedef int Status;
#endif
Linkqueue.h
#ifndef LINKQUEUE_H
#define LINKQUEUE_H
typedef struct QNode
{
int data;//数据域
struct QNode *next;//指针域
}QNode;//队结点类型定义
typedef struct
{
QNode *front;//队首指针
QNode *rear;//队尾指针
}LiQueue;//链队类型定义
Status displayQueue(LiQueue *&lqu);
void initQueue(LiQueue *&lqu);
int isQueueEmpty(LiQueue *lqu);//判断队空
Status EnQueue(LiQueue *&lqu,int x);
Status DeQueue(LiQueue *&lqu,int &x);
#endif
Linkqueue.cpp
#include "init.h"
#include "linkqueue.h"
#include <iostream>
using namespace std;
void initQueue(LiQueue *&lqu)//初始化队列
{
lqu=(LiQueue*)malloc(sizeof(LiQueue));
lqu->front=lqu->rear=NULL;
}
int isQueueEmpty(LiQueue *lqu)//判断队空
{
if (lqu->rear==NULL||lqu->front==NULL) return 1;
else return 0;
}
Status EnQueue(LiQueue *&lqu,int x)//入队
{
QNode *p;
p=(QNode *)malloc(sizeof(QNode));
p->data=x;
p->next=NULL;
if (lqu->rear==NULL) lqu->front=lqu->rear=p;//若队列为空,则新结点为队首结点,也是队尾结点
else
{
lqu->rear->next=p;//将新结点链接到队尾,rear指向它。
lqu->rear=p;
}
return 0;
}
Status DeQueue(LiQueue *&lqu,int &x)//出队
{
QNode *p;
if (lqu->rear==NULL) return 0;//队空不能出队
else
p=lqu->front;
if (lqu->front==lqu->rear)
lqu->front=lqu->rear=NULL;//当队列中只有一个结点时需要特殊处理
else
lqu->front=lqu->front->next;
x=p->data;
cout<<"出队元素为:";
free(p);//释放p所占的内存
return 1;
}
Status displayQueue(LiQueue *&lqu)
{
if(lqu->rear==lqu->front) return 0;
QNode *p;
p=lqu->front;
cout<<"打印队列:";
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
demo.cpp
#include "init.h"
#include "linkqueue.h"
#include <iostream>
using namespace std;
int main()
{
int x;
LiQueue *lqu;
initQueue(lqu);
EnQueue(lqu,1);
EnQueue(lqu,2);
EnQueue(lqu,3);
EnQueue(lqu,4);
EnQueue(lqu,5);
EnQueue(lqu,6);
displayQueue(lqu);
if(DeQueue(lqu,x)==1) cout<<x<<endl;
displayQueue(lqu);
EnQueue(lqu,7);
EnQueue(lqu,8);
EnQueue(lqu,9);
EnQueue(lqu,10);
if(DeQueue(lqu,x)==1) cout<<x<<endl;
EnQueue(lqu,11);
EnQueue(lqu,12);
EnQueue(lqu,13);
EnQueue(lqu,14);
displayQueue(lqu);
system("pause");
getchar();
return 0;
}
运行: