c++链接队列模板类

#include <iostream>
using namespace std;

template <class elemType>
class queue {
public:
    virtual bool isEmpty() = 0;
    virtual void enQueue(const elemType &x) = 0;
    virtual elemType deQueue() = 0;
    virtual elemType getHead() = 0;
    virtual ~queue() {}
};

template<class elemType>
class linkQueue :public queue<elemType> {
private:
    struct node {
        elemType data;
        node *next;
        node(const elemType &x, node *N = NULL) {
            data = x;
            next = N;
        }
        node() :next(NULL) {}
        ~node() {}
    };
    node*front, *rear;
public:
    linkQueue() {
        front = rear = NULL;
    }
    ~linkQueue();
    bool isEmpty() {
        return front == NULL;
    }
    void enQueue(const elemType &x);
    elemType deQueue();
    elemType getHead() {
        return front->data;
    }
};

template <class elemType>
linkQueue<elemType>::~linkQueue() {
    node *tmp;
    while (front != NULL) {
        tmp = front;
        front = front->next;
        delete tmp;
    }
}

template <class elemType>
void linkQueue<elemType>::enQueue(const elemType &x) {
    if (rear == NULL)
        front = rear = new node(x);
    else {
        rear->next = new node(x);
        rear = rear->next;
    }
}

template <class elemType>
elemType linkQueue<elemType>::deQueue() {
    node *tmp = front;
    elemType value = front->data;
    front = front->next;
    if (front == NULL)
        rear = NULL;
    delete tmp;
    return value;
}

int main() {
    linkQueue<int> q;
    cout << q.isEmpty() << endl;
    for (int i = 0; i < 10; ++i)
        q.enQueue(i);
    for (int i = 0; i < 10; ++i) {
        cout<<q.deQueue()<<endl;
    }
    return 0;
}

版权声明:本文为jmpan_sjtu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。