练习8——队列
1、队列的抽象类,虚函数,纯虚函数。
class Queue{
public:
Queue(){};
~Queue(){};
virtual int EnQueue(int x)=0;
virtual int DeQueue(int &x)=0;
virtual int getFront(int &x)=0;
virtual int IsEmpty()const=0;
virtual int IsFull()const=0;
};
2、循环队列
#include <iostream>
#include <assert.h>
using namespace std;
class SeqQueue{
protected:
int rear,front;
int *elements;
int maxSize;
public:
SeqQueue(int sz=10);
~SeqQueue(){delete[] elements;}
int EnQueue(int &x);
int DeQueue(int &x);
int getFront(int &x);
void makeEmpty(){front=rear=0;}
int IsEmpty()const {return front==rear;}
int IsFull()const{
return ((rear+1)%maxSize==front);
}
int getSize()const{
return (rear-front+maxSize)%maxSize;
}
void output();
};
SeqQueue::SeqQueue(int sz) {
front=rear=0;
maxSize=sz;
elements=new int[maxSize];
assert(elements!=NULL);
}
int SeqQueue::EnQueue(int &x) {
if(IsFull()){
return 0;
}
elements[rear]=x;
rear=(rear+1)%maxSize;
return 1;
}
int SeqQueue::DeQueue(int &x) {
if(IsEmpty()){
return 0;
}
x=elements[front];
front=(front+1)%maxSize;
return 1;
}
void SeqQueue::output() {
int i=front;
while(i!=rear){
cout<<elements[i]<<endl;
i=(i+1)%maxSize;
}
}
int main(){
SeqQueue s;
for(int i=0;i<3;i++){
s.EnQueue(i);
}
s.output();
}
3、链式队列
#include <iostream>
using namespace std;
struct QueueNode{
int data;
QueueNode *link;
QueueNode(int d=0,QueueNode *next=NULL):data(d),link(next){}
};
class LinkedQueue{
private:
QueueNode *front,*rear;
public:
LinkedQueue():front(NULL),rear(NULL){}
~LinkedQueue(){MakeEmpty();}
void MakeEmpty();
int EnQueue(int &x);
int DeQueue(int &x);
int GetFront(int &x);
int IsEmpty()const{
return (front==NULL)?1:0;
}
int getSize()const;
void output();
};
void LinkedQueue::MakeEmpty() {
QueueNode *p;
while(front!=NULL){
p=front;front=front->link;delete p;
}
}
int LinkedQueue::EnQueue(int &x) {
if(front==NULL){
front=rear=new QueueNode(x);
}
else{
rear->link=new QueueNode(x);
rear=rear->link;
}
}
int LinkedQueue::DeQueue(int &x) {
if(IsEmpty()){
return 0;
}
QueueNode *p=front;
x=front->data;
front=front->link;
delete p;
return 1;
}
int LinkedQueue::GetFront(int &x) {
if(IsEmpty()){
return 0;
}
x=front->data;
return 1;
}
int LinkedQueue::getSize() const {
QueueNode *p=front;
int k=0;
while(p!=NULL){
k++;
p=p->link;
}
return k;
}
void LinkedQueue::output() {
QueueNode *p=front;
int i=0;
while(p!=NULL){
cout<<++i<<":"<<p->data<<endl;
p=p->link;
}
}
int main(){
LinkedQueue l;
for(int i=0;i<3;i++){
l.EnQueue(i);
}
l.output();
}