《数据结构》读书笔记 第三章 非循环顺序队列的基本操作(出队列时候移除元素)
Queue.h:头文件,定义了参数和基本操作
#include <iostream>
enum {QIS=10,QI=2};
enum {WRONG=-1,OK=0};
typedef int Elem;
typedef struct
{
Elem *base;
int rear;
int memsize;
}Queue;
typedef int Status;
Status InitQueue(Queue &Q)
{
Q.base=new Elem[QIS];
if(Q.base==NULL)
return WRONG;
Q.rear=0;
Q.memsize=QIS;
return OK;
}
void ClearQueue(Queue &Q)
{
Q.rear=0;
}
void DestroyQueue(Queue &Q)
{
delete Q.base;
Q.base=NULL;
Q.memsize=Q.rear=0;
}
bool QueueEmpty(Queue Q)
{
return Q.rear==0;
}
int QueueLen(Queue Q)
{
return Q.rear;
}
Status GetHead(Queue Q,Elem &e)
{
if(Q.rear==0)
return WRONG;
e=Q.base[0];
return OK;
}
Status EnQueue(Queue &Q,Elem e)
{
if(Q.rear>=Q.memsize)
{
Elem *p;
p=new Elem[QIS+QI];
if(p==NULL)
return WRONG;
memcpy(p,Q.base,QIS*sizeof(Elem));
delete Q.base;
Q.base=p;
Q.memsize+=QI;
}
Q.base[Q.rear++]=e;
return OK;
}
Status DeQueue(Queue &Q,int &e)
{
if(Q.rear==0)
return WRONG;
int i;
e=Q.base[0];
for(i=0;i<Q.rear;i++)
Q.base[i]=Q.base[i+1];
Q.rear--;
return OK;
}
void QueueTraverse(Queue Q,void(*vi)(Elem e))
{
int i;
for(i=0;i<Q.rear;i++)
vi(Q.base[i]);
}
Main.cpp:主函数,验证
#include "Queue.h"
using namespace std;
void print(Elem e)
{
cout<<e<<" ";
}
int main()
{
Queue Q;
InitQueue(Q);
int i,tmp;
for(i=1;i<=5;i++)
EnQueue(Q,i);
cout<<"五个元素入队"<<endl<<"遍历队列:";
QueueTraverse(Q,print);
cout<<endl<<"是否是空队列?(1为空)"<<QueueEmpty(Q);
if(DeQueue(Q,tmp)==OK)
cout<<endl<<"出队一个元素,其值为"<<tmp<<endl;
cout<<"队列长度"<<QueueLen(Q)<<endl;
cout<<"遍历队列:";
QueueTraverse(Q,print);
cout<<"清空队列!"<<endl;
ClearQueue(Q);
cout<<"是否是空队列?(1为空)"<<QueueEmpty(Q)<<endl;
return 0;
}