链队列 C++实现

#include <iostream>
using namespace std;
template<class T>
struct Node {
    T data;
    Node* next;
};
template<class T>
class LinkQueue
{
    public:
        LinkQueue();
        ~LinkQueue();
        void EnQueue(T x);
        T DeQueue();
        T Gethead();
        bool Empty();
    private:
        Node<T> *front;
        Node<T> *rear;
};
template<class T>
LinkQueue<T>::LinkQueue()
{
    front=new Node<T>;
    front->next=NULL;
    rear=front;
}
template<class T>
LinkQueue<T>::~LinkQueue()
{
    cout<<"析构函数被调用!"<<endl;
    while(!Empty())
    {
        cout<<"执行一次出队操作,释放元素: "<<DeQueue()<<endl;
    }
    if(Empty())
    {
        delete front;
        cout<<"内存已全部释放";
    }
}
template<class T>
void LinkQueue<T>::EnQueue(T x)
{
    Node<T> *p;
    p=new Node<T>;
    p->data=x;
    p->next=rear->next;
    rear->next=p;
    rear=p;
}
template<class T>
T LinkQueue<T>::DeQueue()
{
    T x;
    if(rear==front){throw "下溢";}
    Node<T> *p;
    p=front->next;
    x=p->data;
    front->next=p->next;
    if(front->next==NULL)
    {
        rear=front;
    }
    delete p;
    return x;
}
template<class T>
T LinkQueue<T>::Gethead()
{
    return front->next->data;
}
template<class T>
bool LinkQueue<T>::Empty()
{
    if(front==rear)
    {
        return true;
    }
    else
    {
        return false;
    }
}
int main()
{
    int x;
    LinkQueue<int> lq;
    cout<<"对6、7、8执行入队操作:"<<endl;
    lq.EnQueue(6);
    lq.EnQueue(7);
    lq.EnQueue(8);
    cout<<"当前队头元素为:"<<lq.Gethead()<<endl;
    try
    {
        cout<<"请输入要入队的元素"<<endl;
        cin>>x;
        lq.EnQueue(x);
    }catch(const char *str){cout<<str<<endl;}

    try
    {
        x=lq.DeQueue();
        cout<<"执行一次出队操作,删除元素: "<<x<<endl;
    }catch(const char *str){cout<<str<<endl;}
    if(lq.Empty())
    {
        cout<<"队列为空"<<endl;
    }
    else
    {
        cout<<"队列非空"<<endl;
    }
//    cout<<"依次执行出队操作,直至队空:"<<endl;
//    while(!lq.Empty())
//    {
//        try
//        {
//            x=lq.DeQueue();
//            cout<<"执行一次出队操作,删除元素: "<<x<<endl;
//        }catch(const char *str){cout<<str<<endl;}
//    }
    if(lq.Empty())
    {
        cout<<"队列为空"<<endl;
    }
    else
    {
        cout<<"队列非空"<<endl;
    }
    return 0;
}

运行结果:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值