C++队列实现
1、顺序队列
#include "iostream"
using namespace std;
template<class Elem>
class Queue{
public:
virtual void clear()=0;
virtual bool enqueue(const Elem& it)=0;
virtual bool dequeue(Elem& it)=0;
virtual bool frontValue(Elem& it)=0;
virtual int lenght()=0;
virtual void print()=0;
};
template<class Elem>
class AQueue:public Queue<Elem>{
private:
int size;
int front;
int rear;
Elem* Array;
public:
AQueue(int Size){
rear=0;
front=1;
size=Size;
Array=new Elem[size];
}
~AQueue(){
clear();
}
void clear(){
front=1;
rear=0;
}
bool dequeue(Elem& it){
if(lenght()==0) return false;
it=Array[front];
front =(front+1)%size;
return true;
}
bool enqueue(const Elem& it){
if(lenght()==size) return false;
rear=(rear+1)%size;
Array[rear]=it;
return true;
}
int lenght(){
return (rear+size-front+1)%size;
}
bool frontValue(Elem& it){
if(lenght()==0) return false;
it=Array[front];
return true;
}
void print(){
if(lenght()==0) return;
int Front=front;
int count=0;
while(lenght()!=count){
cout <<Array[(Front++)%size]<<" ";
count++;
}
cout <<endl;
}
};
int main(int argc, char* argv[])
{
AQueue<int> aQueue(10);
aQueue.enqueue(8);
aQueue.enqueue(2);
aQueue.enqueue(11);
aQueue.enqueue(12);
aQueue.enqueue(13);
aQueue.enqueue(15);
aQueue.enqueue(14);
aQueue.print();
int j;
aQueue.dequeue(j);
aQueue.dequeue(j);
aQueue.dequeue(j);
aQueue.dequeue(j);
aQueue.enqueue(16);
aQueue.enqueue(17);
aQueue.enqueue(18);
aQueue.enqueue(19);
aQueue.print();
return 0;
}
2、链表队列
template<class Elem>
class Link {
public:
Elem element; // Elem value for this node
Link *next; // Pointer to next node in list
Link(const Elem elemval, Link* nextval =NULL)
{
element = elemval; next = nextval;
}
Link(Link* nextval =NULL) {
next = nextval;
}
};
template<class Elem>
class LQueue:public Queue<Elem>{
private:
Link<Elem>* front;
Link<Elem>* rear;
int size;
public:
LQueue(){
front=rear=NULL;
size=0;
}
~LQueue(){
clear();
}
void clear(){
size=0;
while(rear!=NULL){
front=rear;
rear=rear->next;
delete front;
}
front=NULL;
}
bool dequeue(Elem& it){
if(size==0) return false;
it=front->element;
Link<Elem>* temp=front;
front=front->next;
delete temp;
if(front==NULL) rear=NULL;
size--;
return true;
}
bool enqueue(const Elem& it){
if(front==NULL)
front=rear=new Link<Elem>(it,NULL);
else{
rear->next=new Link<Elem>(it,NULL);
rear=rear->next;
}
size++;
return true;
}
bool frontValue(Elem& it){
if(size==0) return false;
it=front->element;
return true;
}
int lenght(){
return size;
}
void print(){
Link<Elem>* temp=front;
while(temp!=NULL){
cout <<temp->element<<" ";
temp=temp->next;
}
cout <<endl;
}
};
int main(int argc, char* argv[])
{
LQueue<int> lQueue;
lQueue.enqueue(12);
lQueue.enqueue(1);
lQueue.enqueue(2);
lQueue.enqueue(3);
lQueue.enqueue(4);
lQueue.enqueue(5);
lQueue.enqueue(6);
lQueue.enqueue(7);
lQueue.enqueue(8);
lQueue.print();
int i;
lQueue.dequeue(i);
cout <<i<<endl;
lQueue.print();
lQueue.frontValue(i);
cout <<i<<endl;
return 0;
}