队列的实验

链队列

头文件:

#ifndef linkQueue_H

#define linkQueue_H

 

template

struct Node

{

        datatypedata;

        Node*next;

};

 

template

class linkQueue

{

        public:

                linkQueue();

                ~linkQueue();

                voidEnQueue(datatype x);

                datatypeDeQueue();

                datatypeGetQueue();

                intEmpty();

        private:

                Node*front,*rear;

};

#endif;

 

类中成员函数的实现:

#include"linkQueue.h"

 

template

linkQueue::linkQueue()

{

        Node*s=NULL;

        s=newNode;

        s->next=NULL;

        front=rear=s;

}

 

template

linkQueue::~linkQueue()

{

        Node*p=NULL;

        while(front!=NULL)

        {

                p=front->next;

                deletefront;

                front=p;

        }

}

 

template

voidlinkQueue::EnQueue(datatype x)

{

        Node*s=NULL;

        s=newNode;

                s->data=x;

        s->next=NULL;

        rear->next=s;rear=s;

}

 

template

datatypelinkQueue::DeQueue()

{

        Node*p=NULL;

        intx;

        if(rear==front)throw"下溢";

        p=front->next;

        x=p->data;

        front->next=p->next;

        if(p->next==NULL)rear=front;

        deletep;

        returnx;

}

 

template

datatypelinkQueue::GetQueue()

{

        if(front!=rear)

                returnfront->next->data;

}

 

template

int linkQueue::Empty()

{

        if(front==rear)

                return1;

        else

                return0;

}

 

主函数:

#include

using namespace std;

#include"linkQueue.cpp"

 

void main()

{

        linkQueueQ;

        if(Q.Empty())

                cout<<"队列为空"<

        else

                cout<<"队列非空"<

        cout<<"元素10和15执行入队操作:"<

        try

        {

                Q.EnQueue(77);

                Q.EnQueue(88);

        }

        catch(char*wrong)

        {

                cout<

        }

        cout<<"查看队头元素:"<

        cout<

        cout<<"执行出队操作:"<

        try

        {

                Q.DeQueue();

        }

        catch(char*wrong)

        {

                cout<

        }

        cout<<"查看队头元素:"<

        cout<

}

 

 

结果:

队列为空

元素77和88执行入队操作:

查看队头元素:

77

执行出队操作:

查看队头元素:

88


你可能感兴趣的:(队列,数据结构)