手动封装一个循环顺序队列类(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;