题目:
题目一:C++实现顺序栈
题目二:C++实现顺序循环队列
代码:
代码一:
main.cpp
#include <iostream>
#include<text1h.h>
using namespace std;
int main()
{
seqstack a1;
a1.stack_create();
a1.stack_push(2);
a1.stack_push(12);
a1.stack_push(6);
a1.stack_show();
a1.stack_pop();
a1.stack_show();
a1.free();
return 0;
}
text1.h
#ifndef TEXT1H_H
#define TEXT1H_H
#include <iostream>
#define MAX 20
typedef int datatype;
using namespace std;
class seqstack
{
private:
datatype *data;
int top;
public:
void stack_create();
int stack_empty();
int stack_full();
void stack_push(datatype e);
void stack_show();
void stack_pop();
void free();
};
#endif // TEXT1H_H
text1.cpp
#include <iostream>
#include<text1h.h>
using namespace std;
void seqstack::stack_create()
{
data=new datatype[MAX];
top=-1;
cout<<"创建成功"<<endl;
}
int seqstack::stack_empty()
{
return top==-1;
}
int seqstack::stack_full()
{
return top==MAX-1;
}
void seqstack::stack_push(datatype e)
{
if(data==nullptr||stack_full())
{
cout<<"入栈失败"<<endl;
return;
}
top++;
data[top]=e;
cout<<"入栈成功"<<endl;
}
void seqstack::stack_show()
{
if(data==nullptr||stack_empty())
{
cout<<"遍历失败"<<endl;
return;
}
cout<<"栈中从栈顶到栈底元素分别是:";
for(int i=top;i>=0;i--)
{
cout<<data[i]<<" ";
}
cout<<endl;
}
void seqstack::stack_pop()
{
if(data==nullptr||stack_empty())
{
cout<<"出栈失败"<<endl;
return;
}
cout<<data[top]<<endl;
top--;
}
void seqstack::free()
{
delete []data;
data = nullptr;
cout << "销毁成功" << endl;
}
代码二:
main.cpp
#include <iostream>
#include<text2h.h>
using namespace std;
int main()
{
sequeue a1;
a1.queue_create();
a1.queue_push(1);
a1.queue_push(2);
a1.queue_push(5);
a1.queue_show();
a1.queue_pop();
a1.queue_show();
a1.free();
return 0;
}
text2.h
#ifndef TEXT2H_H
#define TEXT2H_H
#include <iostream>
#define MAX 8
typedef int datatype;
using namespace std;
class sequeue
{
private:
datatype *data;
int front;
int tail;
public:
void queue_create();
int queue_empty();
int queue_full();
void queue_push(datatype e);
void queue_pop();
void queue_show();
int queue_size();
void free();
};
#endif // TEXT2H_H
text2.cpp
#include<text2h.h>
void sequeue::queue_create()
{
data=new datatype[MAX];
if(data==nullptr)
{
cout<<"创建失败"<<endl;
return;
}
front=0;
tail=0;
cout<<"创建成功"<<endl;
}
int sequeue::queue_empty()
{
return front==tail;
}
int sequeue::queue_full()
{
return (tail+1)%MAX == front;
}
void sequeue::queue_push(datatype e)
{
if(data==nullptr||queue_full())
{
cout<<"入队失败"<<endl;
return;
}
data[tail]=e;
tail=(tail+1)%MAX;
cout<<"入队成功"<<endl;
}
void sequeue::queue_pop()
{
if(data==nullptr||queue_empty())
{
cout<<"出队失败"<<endl;
return;
}
cout<<data[front]<<" ";
front=(front+1)%MAX;
cout<<"出队成功"<<endl;
}
void sequeue::queue_show()
{
if(data==nullptr||queue_empty())
{
cout<<"遍历失败"<<endl;
return;
}
cout<<"队伍中从对头到队尾元素分别是:";
for(int i=front;i!=tail;i=(i+1)%MAX)
{
cout<<data[i]<<" ";
}
cout<<endl;
}
int sequeue::queue_size()
{
return (tail+MAX-front)%MAX;
}
void sequeue::free()
{
delete []data;
data = nullptr;
cout << "销毁成功" << endl;
}
运行结果:
结果一:

结果二:
