c++ day3 作业

  • 手动封装一个循环顺序队列类(Stack)

私有成员属性:存放队列的数组、两个变量分别记录队头和队尾下标

公有成员函数: 入队(push( type value ))

出队(pop())

展示(show)

求队列长度(size()):要求时间复杂度在常量级别

判满( bool full())

判空(bool empty())

  • main.c
#include"03head.h"


int main()
{
    int e;
    string s;
    Stack s1;
    while(1){
        cout<<"输入要入队的元素:";
        cin>>e;
        s1.push(e);
        cout<<"要继续吗?yes/no :";
        cin>>s;
        if(s == "no"){
            break;
        }
    }
    s1.pop();
    s1.show();
    int count = s1.mySize();
    cout<<"个数为:"<<count<<endl;
    return 0;
}
  • test.c
#include"03head.h"

bool Stack:: empty()
{
    return front == rear;
}

bool Stack:: full()
{
    return front == (rear+1)%MAXSIZE;
}

void Stack:: push(int e)
{
    if(full()){
        cout<<"入队失败"<<endl;
        return;
    }
    data[rear]=e;
    rear=(rear+1)%MAXSIZE;
}

void Stack:: pop()
{
    if(empty()){
        cout<<"出队失败"<<endl;
        return;
    }
    cout<<"出队的元素是:"<<data[front]<<endl;
    front=(front+1)%MAXSIZE;
}

void Stack:: show()
{
    if(empty()){
        cout<<"遍历失败"<<endl;
        return;
    }
    for(int i=front;i!=rear;i=(i+1)%MAXSIZE){
        cout<<data[i];
    }
    cout<<endl;
}

int Stack:: mySize()
{
    return (MAXSIZE-front+rear)%MAXSIZE;
}
  • head.h
#ifndef TEST_H
#define TEST_H
#include <iostream>

#define MAXSIZE 5

using namespace std;

class Stack
{
private:
    int data[MAXSIZE];
    int front = 0;
    int rear = 0;
public:
    //判空
    bool empty();

    //判满
    bool full();

    //入队
    void push(int e);

    //出队
    void pop();

    //遍历
    void show();

    //个数
    int mySize();
};
#endif

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值