5.9homework

手动封装一个循环顺序队列类


私有成员属性:存放队列的数组、两个变量分别记录队头和队尾下标
公有成员函数: 入队(push( type value ))
出队(pop())
展示(show)
求队列长度(size()):要求时间复杂度在常量级别
判满( bool full())
判空(bool empty())
 

#include <iostream>


using namespace std;

#define MAXSIZE  8


class stack
{
public:
    void push(int value); //入队

    void pop(); //出队

    void output(); //遍历队列

    bool full(); //判断队满

    bool empty(); //判断队空

    int size(); //求队列长度


private:
    int arr[MAXSIZE]= {0};
    int front = 0; //队头
    int rear = 0; //队尾
};


//入队
void stack::push(int value)
{
    if(full())
    {
        cout<<"队列已满"<<endl;
        return ;
    }
    arr[rear] = value;
    rear = (rear+1)%MAXSIZE;
}

//出队
void stack::pop()
{
    if(empty())
    {
        cout<<"队列为空"<<endl;
        return;
    }
    front = (front+1)%MAXSIZE;
}

//遍历队列
void stack::output()
{
    if(empty())
    {
        cout<<"队列为空"<<endl;
        return;
    }
    cout<<"遍历队列:"<<endl;
    for(int i = front;i != rear;i = (i+1)%MAXSIZE )
    {
        cout<<arr[i] <<endl;
    }
}

//判断队满
bool stack::full()
{
       return (rear+1)%MAXSIZE == front ? true : false;
}

//判断队空
bool stack::empty()
{
     return rear == front ? true : false;
}

//求队列长度
int stack::size()
{
    return (MAXSIZE - front + rear)%MAXSIZE;
}



int main()
{
    stack s1;//
    int data; //存储输入数据
    int n = 0;  //存储数据个数
    cout<<"输入数据个数"<<endl;
    cin>>n;
    //循环输入数据
    for(int i = 0;i<n;i++)
    {
        cout<<"第"<<i+1<<"个数据:";
        cin>>data;
        s1.push(data);
    }
    //遍历数据
    s1.output();
    //队列长度
    cout <<"队列长度 :"<<s1.size()<<endl;
    //出队
    s1.pop();
    cout<<"出队后:"<<endl;
    s1.output();
    //出队后队列长度
    cout <<"出队后队列长度 :"<<s1.size()<<endl;

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值