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