C++ 5月9号

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

#include <iostream>
#define MAXSIZE 10
typedef int datatype;
using namespace std;
class Stack
{
private:
    datatype arr[MAXSIZE];
    int head=0;
    int rear=0;
public:
    //判满
    bool full()
    {
        return (rear+1)%MAXSIZE==head;
    }
    //判空
    bool empty()
    {
        return head==rear;
    }
    //队长
    int size()
    {
        return (rear-head+MAXSIZE)%MAXSIZE;
    }
    //出队
    void pop()
    {
        if(empty())
        {
           cout<<"empty"<<endl;
        }
        else
        {
            head=(head+1)%MAXSIZE;
        }
    }
    //入队
    void push(datatype value)
    {
        if(full())
        {
            cout<<"full"<<endl;
        }
        else
        {
            arr[rear]=value;
            rear=(rear+1)%MAXSIZE;
        }
    }
    //展示
    void show()
    {
        cout<<"遍历结果为:"<<endl;
        for(int i=head;i!=rear;i=(i+1)%MAXSIZE)
        {
            cout<<arr[i]<<endl;
        }
    }
};
int main()
{
    Stack s;
    s.push(1);
    s.push(2);
    s.push(3);
    s.pop();
    s.show();
    int s_size=s.size();
    cout<<"队长:"<<s_size<<endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 C++ 万年历程序,可以输入年份和月份,输出该月份的日历: ``` #include <iostream> using namespace std; // 判断是否是闰年 bool isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; } // 获取某年某月的天数 int getDaysOfMonth(int year, int month) { if (month == 2) { return isLeapYear(year) ? 29 : 28; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else { return 31; } } // 获取某年某月第一天是星期几 int getFirstDayOfWeek(int year, int month) { int y = year; int m = month; if (m == 1 || m == 2) { m += 12; y--; } int d = 1; int w = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7; return w; } // 输出日历 void printCalendar(int year, int month) { cout << " " << year << "年" << month << "月" << endl; cout << "日 一 二 三 四 五 六" << endl; int firstDayOfWeek = getFirstDayOfWeek(year, month); int daysOfMonth = getDaysOfMonth(year, month); int day = 1; for (int i = 0; i < 6; i++) { for (int j = 0; j < 7; j++) { if (i == 0 && j < firstDayOfWeek) { cout << " "; } else if (day > daysOfMonth) { break; } else { printf("%2d ", day++); } } cout << endl; if (day > daysOfMonth) { break; } } cout << endl; } int main() { int year, month; cout << "请输入年份和月份:" << endl; cin >> year >> month; printCalendar(year, month); return 0; } ``` 注意:这只是一个简单的实现,还有很多细节需要考虑,比如输入的年份和月份是否合法,输出的格式是否美观等等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值