数据结构5_链队列

本文用指针形式实现了先进先出的队列,与栈队列类似,需要设计一个队列节点类,一个队列类,
同时队列类为节点类的友元函数;不过与链栈不同的是,链栈仅用单一指针来实现入栈和出栈
而链队列需要有front和rear两个指针(皆为队列节点类指针),front指针负责处理出列,rear处理入列
#include<iostream>
using namespace std;
class LinkQueue;
class QNode   //每个节点的类
{
    char *data;    //每个节点的数据类型
    QNode *next;   //QNode指针,指向下一个节点
    friend class LinkQueue;
};
class LinkQueue
{
    QNode *front;//队头指针
    QNode *rear;//队尾指针
public:
    LinkQueue()//构造一个新的队列,
    {
        front=rear=NULL;//想把队头和队尾指针置为无,否则if语句中!front判定将始终为1
        front=rear=new QNode;
        if(!front)
        {
            cout<<"OVERFLOW"<<endl;
            return;
        }
        front->next=NULL;     
        cout<<"the queue is constructed"<<endl;
    }
    void EnQueue(char *e)//插入队尾,
    {
        QNode *p=new QNode;//分配一个队列节点空间,
        if(!p)
        {
            cout<<"OVERFLOW"<<endl;
            return;
        }
        p->data=new char(sizeof(e)+1);
        strcpy(p->data,e);
        p->next=NULL;
        rear->next=p;    //队尾节点的next指针指向p
        rear=p;            //队尾节点指向p
    }
    bool QueueEmpty()
    {
        if (front==rear)
            return true;
        else
            return false;
    }
    void DeQueue(char *&e)//队头出列
    {
        if(QueueEmpty()) //空队列报错
        {
            cout<<"error"<<endl;
            return;
        }
        QNode *p=front->next;
        e=new char(sizeof(p->data)+1);
        strcpy(e,p->data);
        front->next=p->next;
        if(rear==p)      //队列只有一个节点的情况
            rear=front;
        delete p;
    }
    void QueueClear()   //队列清空
    {
       
        QNode *p;
        while(!QueueEmpty())   //队列非空时执行
        {
            p=front->next;
            front->next=p->next;
            if(rear==p)      //队列只有一个节点的情况
                rear=front;
            delete p;
        }
        cout<<"all cleared"<<endl;
    }
    int QueueLength()   //统计队列长度
    {
        if(QueueEmpty())
            return 0;
        else
        {
            QNode *p=front->next;
            int length=1;
            while(p!=rear)
            {
                length++;
                p=p->next;
            }
            return length;

        }
    }
};


void main()
{
    LinkQueue a;

    a.EnQueue("yige");
    a.EnQueue("liangge");
    a.EnQueue("sange");
    cout<<"当前队列长度是:"<<a.QueueLength()<<endl;
    char *q;
    a.DeQueue(q);
    cout<<"当前队列长度是:"<<a.QueueLength()<<endl;
    cout<<"出列的是"<<q<<endl;
    a.QueueClear();
    cout<<"当前队列长度是:"<<a.QueueLength()<<endl;
}




posted on 2014-05-23 17:24  zhuangwy_CV  阅读(249)  评论(0编辑  收藏  举报

导航