C++面向对象实现链式队列——第一篇博客

C++面向对象实现链式队列

结点类:

class LinkNode
{
public:

    int data;
    LinkNode *next;
};

队列类:

class LQueue
{
    public:
        LQueue();
        virtual ~LQueue();              //析构函数
        void InitQueue(LQueue &);       //初始化队列
        void EnQueue(LQueue &,int&);    //入队
        void TraverseQueue(LQueue &);   //遍历
        bool isEmpty(LQueue &);         //判空
        bool DelQueue(LQueue&,int&);
    protected:
    
    private:
      LinkNode *front,*rear;
};
LQueue::LQueue()
{
    //ctor
}

LQueue::~LQueue()
{
    //dtor
}

//初始化队列
void LQueue::InitQueue(LQueue &LQ)
{
    LQ.front=LQ.rear= new LinkNode [sizeof(LinkNode)];//创建头结点,头结点不保存数据
    LQ.front->next=NULL;
}

//入队
void LQueue::EnQueue(LQueue &LQ,int& val)
{
    LinkNode* q=LQ.rear;
    LinkNode* p=(LinkNode*)malloc(sizeof(LinkNode));
    p->data=val;
    p->next=NULL;
    q->next=p;
    LQ.rear=p;
}

//判空
bool LQueue::isEmpty(LQueue &LQ)
{
    if(LQ.front==LQ.rear)
        return true;
    else
        return false;

}

//遍历
void LQueue::TraverseQueue(LQueue &LQ)
{
    LinkNode* p;
    if(isEmpty(LQ))
    {
        cout<<"空队列!"<<endl;
        return;
    }
    p=LQ.front->next;
    while(p!=NULL)
    {
        cout<<"元素为"<<p->data<<endl;
        p=p->next;
    }
}
//出队
bool LQueue::DelQueue(LQueue& LQ,int&x)
{
    if(isEmpty(LQ))
        return false;
    LinkNode *p=LQ.front->next;
    x=p->data;
    LQ.front->next=p->next;
    if(LQ.rear==p)
        LQ.rear=LQ.front;   //当队伍中只有一个元素时,出队后就为空
    free(p);
    return true;
}


主函数

#include <iostream>
#include <malloc.h>
using namespace std;

int main()
{
    int x[]={2,3,4,6};
    int val=0;
    LQueue Lq;
    LQueue LQ2;
    LQueue Q;
    Lq.InitQueue(Q);
    Lq.InitQueue(LQ2);
    for(int i=0;i<(int)(sizeof(x)/sizeof(int));i++)
    {
        Lq.EnQueue(Q,x[i]);
    }
    cout<<"Q队伍为"<<endl;
    Lq.TraverseQueue(Q);
    Lq.DelQueue(Q,val);
    cout<<"出队元素为\t"<<val<<endl;
    cout<<"出队后"<<endl;
    Lq.TraverseQueue(Q);
    cout<<"LQ2队伍为";
    Lq.TraverseQueue(LQ2);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值