1.顺序队列的实现
#include <cstdlib>
#include <iostream>
using namespace std;
template <class Type>
class Queue
{
private:
Type *q;
int front,rear,max;
public:
Queue(int m):max(m)
{
q=new Type(max);
rear=front=0;
}
~Queue()
{
delete[] q;
}
bool Add(Type item);
bool Del(Type &item);
bool QueueEmpty();
bool QueueFull();
};
template <class Type>
bool Queue<Type>::QueueEmpty()
{
if(front==rear)
return true;
else
return false;
}
template <class Type>
bool Queue<Type>::QueueFull()
{
if((rear+1)%max==front)
return true;
else
return false;
}
template <class Type>
bool Queue<Type>::Add(Type item)
{
if(QueueFull())
{
cout<<"Queue if full"<<endl;
return false;
}
else
{
q[rear]=item;
rear=(rear+1)%max;
return true;
}
}
template <class Type>
bool Queue<Type>::Del(Type &item)
{
if(QueueEmpty())
{
cout<<"Queue is empty!"<<endl;
return false;
}
else
{
item=q[front];
front=(front+1)%max;
return true;
}
}
int main(int argc, char *argv[])
{
Queue<int> *q=new Queue<int>(10);
q->Add(4);
q->Add(5);
int i=0;
q->Del(i);
cout<<i<<endl;
q->Del(i);
cout<<i<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
2.链式队列的实现
#include <cstdlib>
#include <iostream>
using namespace std;
template <class Type>
class LinkedQueue
{
private:
struct node
{
Type data;
struct node *link;
};
struct node *top,*rear;
public:
LinkedQueue()
{
rear=top=NULL;
}
~LinkedQueue()
{
node *temp;
while(top)
{
temp=top;
top=top->link;
delete temp;
}
}
bool Add(Type item);
bool Del(Type &item);
bool QueueEmpty();
};
template <class Type>
bool LinkedQueue<Type>::QueueEmpty()
{
if(top==NULL)
return true;
else
return false;
}
template <class Type>
bool LinkedQueue<Type>::Add(Type item)
{
node *t=new node;
if(t==NULL)
{
cout<<"out of space!"<<endl;
return false;
}
else
{
t->data=item;
t->link=NULL;
if(rear==NULL)
{
top=t;
rear=t;
}
else
{
rear->link=t;
rear=t;
}
return true;
}
}
template <class Type>
bool LinkedQueue<Type>::Del(Type &item)
{
if(QueueEmpty())
{
cout<<"Queue is empty!"<<endl;
return false;
}
else
{
node *t;
t=top;
item=t->data;
if(top==rear)
{
top=NULL;
rear=NULL;
}
else
{
top=top->link;
}
delete t;
return true;
}
}
int main(int argc, char *argv[])
{
LinkedQueue<int> *q=new LinkedQueue<int>();
q->Add(4);
q->Add(5);
int i=0;
q->Del(i);
cout<<i<<endl;
q->Del(i);
cout<<i<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}