顺序队列之C++实现

时间:2022-03-09 20:08:31

下面介绍下用C++实现的顺序队列,在VC6下调试通过。

1、文件组织形式

顺序队列之C++实现

2、sq.h顺序队列类的说明

#ifndef _SQ_H_
#define _SQ_H_ typedef int dataType;
#define maxSize 100 class sq
{
public:
sq();
//~sq();
void push(dataType var);
void pop();
dataType front();
bool isEmpty();
bool isFull(); private:
dataType queue[maxSize];
int head;
int tail;
}; #endif

3、sq.cpp顺序队列类的定义

#include <iostream>
#include "sq.h"
using namespace std; sq::sq()
{
head = -1;
tail = -1;
} void sq::push(dataType var)
{
queue[++tail] = var; if(tail == 0)
{
head = 0;
}
} void sq::pop()
{
++head;
} dataType sq::front()
{
return queue[head];
} bool sq::isEmpty()
{
bool flag = head > tail; //当head和tail不为-1时 if(head == -1 && tail == -1) //当head=tail=-1时
{
flag = true;
} if(flag)
{
head = tail = -1;
} return flag;
} bool sq::isFull()
{
return tail == maxSize-1;
}

4、main.cpp

#include <iostream>
#include "sq.h"
using namespace std; int main()
{
sq exp;
int i = 0; for(i=0;i<maxSize+10;++i)
{
if(!exp.isFull())
{
exp.push(i);
}
} for(i=0;i<maxSize+20;++i)
{
if(!exp.isEmpty())
{
cout<<exp.front()<<endl;
exp.pop();
}
} if(exp.isEmpty())
{
cout<<"队列已空!"<<endl;
} return 0;
}