C++中的循环顺序队列的创建,出队,入队与遍历,销毁

main文件:

#include <iostream>
#include "queue.h"
using namespace std;

int main()
{
    queue q;
    //创建循环顺序栈
    q.create();
    //入栈
    q.push(1);
    q.push(8);
    q.push(5);
    q.push(2);
    q.push(6);
    q.push(4);
    //遍历
    q.show();

    //出队
    q.pop();
    q.pop();
    q.pop();
    //遍历
    q.show();
    //销毁
    q.destroy();

    return 0;
}

实现效果:

.h文件:

#ifndef QUEUE_H
#define QUEUE_H

#define MAX 20
typedef int datatype;

class queue
{
private:
    datatype *data;
    int front;
    int tail;
public:
    //创建
    void create();

    //判空
    bool empty();

    //判满
    bool full();

    //入队
    void push(datatype e);

    //出队
    void pop();

    //遍历
    void show();

    //销毁
    void destroy();

};

#endif // QUEUE_H

.c文件:

#include <iostream>
#include "queue.h"
using namespace std;

//创建
void queue::create()
{
    data = new datatype[MAX];
    front = tail = 0;
}
//判空
bool queue::empty()
{
    return front == tail;
}
//判满
bool queue::full()
{
    return front == (tail+1)%MAX;
}
//入队
void queue::push(datatype e)
{
    if(full())
    {
        cout<<"队已满,无法入队"<<endl;
        return;
    }
    data[tail] = e;
    tail = (tail+1)%MAX;
}
//出队
void queue::pop()
{
    if(empty())
    {
        cout<<"队已空,无法出队"<<endl;
        return;
    }
    front = (front+1)%MAX;
}
//遍历
void queue::show()
{
    if(empty())
    {
        cout<<"队已空,无法遍历"<<endl;
        return;
    }
    for(int i = front;i != tail;i = (i+1)%MAX)
    {
        cout<<data[i]<<" ";
    }
    cout<<endl;
}

//销毁
void queue::destroy()
{
    delete []data;
    data = nullptr;
}

在判满与遍历的时候需要注意顺序队列的循环特征。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值