队列的实现

结点结构体:

template<class ElemType>
struct Node {
    ElemType data;
    Node<ElemType>* next;
    Node();
    Node(const ElemType& e, Node<ElemType>* Link = NULL);
};
template<class ElemType>
Node<ElemType>::Node() {
    next = NULL;
}
template<class ElemType>
Node<ElemType>::Node(const ElemType& e, Node<ElemType>* link) {
    data = e;
    next = link;
}

队列:

template<class ElemType>
class LinkQueue   //链队列
{
protected:
    //数据成员
    Node<ElemType>* front, * rear;//队头队尾指针
    int count;

public:
    LinkQueue();
    void Traverse(void(*visit)(const ElemType&))const;
    virtual ~LinkQueue();
    int Length()const;
    bool InQueue(const ElemType& e);
    bool OutQueue(ElemType& e);
    bool OutQueue();
    void Clear();
    bool Empty()const;
};
template<class ElemType>
LinkQueue<ElemType>::LinkQueue()
{
    rear = front = new Node<ElemType>;
    count = 0;
}

template<class ElemType>
void LinkQueue<ElemType>::Clear()
{
    while (!Empty())
    {
        OutQueue();
    }
}

template<class ElemType>
bool LinkQueue<ElemType>::Empty()const
{
    return count == 0;
}

template<class ElemType>
LinkQueue<ElemType>::~LinkQueue()
{
    Clear();
    delete front;
}

template<class ElemType>
int LinkQueue<ElemType>::Length()const
{
    return count;
}

template<class ElemType>
bool LinkQueue<ElemType>::InQueue(const ElemType& e)
{
    Node<ElemType>* temPtr = new Node<ElemType>(e);
    if (temPtr == NULL)
    {
        return false;
    }
    else
    {
        rear->next = temPtr;
        rear = temPtr;
        count++;
        return true;
    }

}

template<class ElemType>
bool LinkQueue<ElemType>::OutQueue(ElemType& e)
{
    if (!Empty())
    {
        Node<ElemType>* temPtr = front->next;
        e = temPtr->data;
        front->next = temPtr->next;
        if (rear == temPtr)
        {
            rear = front;
        }
        delete temPtr;
        count--;
        return true;
    }
    else
    {
        return false;
    }
}

template<class ElemType>
bool LinkQueue<ElemType>::OutQueue()
{
    if (!Empty())
    {
        Node<ElemType>* temPtr = front->next;
        front->next = temPtr->next;
        if (rear == temPtr)
        {
            rear = front;
        }
        delete temPtr;
        count--;
        return true;
    }
    else
    {
        return false;
    }
}
template<class ElemType>
void LinkQueue<ElemType>::Traverse(void(*visit)(const ElemType&))const {
    for (Node<ElemType>*temptr=front->next;temptr!=NULL;temptr=temptr->next){
        (*visit)(temptr->data);
    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值