链式队列

来源:互联网 发布:php curl 传图片 编辑:程序博客网 时间:2024/06/06 00:10

链式队列。基本上所有操作都是单链表的操作

/*  Author : Moyiii *  Mail:  lc09@vip.qq.com *  链式队列的实现 *  仅作学习之用,当然如果你想拿去用,随你好啦。 *  如果发现BUG,或你有更好的想法,欢迎反馈给我*/#include <iostream>using namespace std;class Node{public:    int data;    Node *next;};class LinkQueue{public:    LinkQueue();    ~LinkQueue();    void clear();    bool isEmpty();    int getLength();    bool getHead(int &e);//获得队列头    bool enQueue(int e);//入队列    bool deQueue();//出队列    void print();//打印(不是打印数组,是打印队列)private:    Node *front;//头结点,next指向队列的头    Node *rear;//尾节点,指向队列尾};LinkQueue :: LinkQueue(){    if( !front )    {        cout << "Space Malloc Error!" << endl;        return;    }    front = rear = new Node;    front->next = NULL;}//从队列链表尾部插入节点bool LinkQueue :: enQueue(int e){    Node *node = new Node;    if( !node )    {        cout << "Space Malloc Error!" << endl;        return false;    }    node->data = e;    node->next = NULL;    rear->next = node;    rear = node;    return true;}bool LinkQueue :: getHead(int &e){    if(front == rear)    {        cout << "Queue is Empty,getHead Error!" << endl;        return false;    }    e = front->next->data;    return true;}//删除头结点的下一个节点bool LinkQueue :: deQueue(){    if(front == rear)    {        cout << "Queue is Empty,deQueue Error!" << endl;        return false;    }    Node *p = front->next;    front->next = p->next;    if(p == rear)    {        rear = front;    }    delete p;    return true;}bool LinkQueue :: isEmpty(){    return (front == rear);}//遍历,故意没有使用length变量int LinkQueue :: getLength(){    Node *p = front->next;    int count = 0;    while(p != NULL)    {        count++;        p = p->next;    }    return count;}//遍历删除void LinkQueue :: clear(){    while(front->next != NULL)    {        Node *p = front->next;        front->next = p->next;        delete p;    }    rear = front;}LinkQueue :: ~LinkQueue(){    clear();    delete front;}void LinkQueue :: print(){    Node *p = front->next;    while(p != NULL)    {        cout << p->data << " ";        p = p->next;    }    cout << endl;}int main(){    LinkQueue myQueue;    //除了上边的声明方式不同,下边和循环队列一样,操作都是相同的    for(int i = 1; i <= 15; ++i)    {        myQueue.enQueue(i);    }    myQueue.print();    int e;    for(int i = 1; i <= 5; ++i)    {        myQueue.getHead(e);        cout << "Head:" << e << endl;        myQueue.deQueue();    }    for(int i = 1; i <= 3; ++i)    {        myQueue.enQueue(i);    }    cout << myQueue.getLength() << endl;    myQueue.print();    return 0;}


0 0
原创粉丝点击