首页 > 代码库 > LinkQueue

LinkQueue

template <class T>
class Node
{
public:
    T data;
    Node *next;
    Node () { }
    Node (T d, Node *p): data(d), next(p) { }
};

template <class T>
class Queue
{
private:
    Node<T> *front, *rear;    
    int size; 
public:
    Queue() : rear(NULL), front(NULL) { size = 0; }
    
    ~Queue() { if(!IsEmpty()) makeEmpty(rear); }
    
    bool EnQueue(const T &x)
    {
        rear = new Node<T> (x, rear);
        size++;
        if(!front) front = rear;
    } 
    
    bool DeQueue(T &x)
    {
        if(IsEmpty()) return false;
        x = front->data;
        
        if(front == rear) delete front;
        else{
            Node<T> *p = front;
            front = rear;
            while(front->next != p) front = front->next;
            delete p;
        }
        
        size--;
        return true;
    }
    
    bool getFront(T &x) const //ok
    {
        if(IsEmpty()) return false;
        x = front->data;
        return true;
    }
    
    void makeEmpty(Node<T> *p)
    {
        if(p != rear) makeEmpty(p->next);
        delete p;
    } 
    
    bool IsEmpty() const { return !size ? true : false; }
    
    int getSize() const 
    {
        return size;
    }
};

Mind:Nothing

LinkQueue