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

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

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

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

出队(pop())

展示(show)

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

判满( bool full())

判空(bool empty())

头文件

#ifndef STACK_H
#define STACK_H
#define MAXSIZE 7
typedef int datatype;

class Stack
{
public:
    Stack();
private:

        datatype data[MAXSIZE];
        int front;
        int rear;

public:

    void push(int value);       //入队
    void pop();                 //出队
    void output();              //遍历
    int size();                 //要求时间复杂度在常量级别
    bool full();
    bool empty();
};

.cpp文件

#include "stack.h"
#include<iostream>
using namespace std;
Stack::Stack()
{
    front = rear = 0;
}


void Stack::push(int value)
{
    if(full())
        return ;
    data[rear] = value;
    rear = (rear+1)%MAXSIZE;
}

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

void Stack::output()
{
    for(int i =front; i !=rear; i = (i+1)%MAXSIZE)
    {
        cout <<"  "<< data[i];
    }
    cout << endl;
}

int Stack::size()
{
    return (MAXSIZE -front +rear)%MAXSIZE;
}

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

main.c

int main()
{
    Stack s;

    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);
    s.push(5);
    s.push(6);
    s.output();
    s.pop();
    s.pop();

    s.output();
    cout <<"队列的长度 = "<< s.size()<< endl;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值