1> 自行封装一个栈的类,包含私有成员属性:栈的数组、记录栈顶的变量
成员函数完成:构造函数、析构函数、拷贝构造函数、入栈、出栈、清空栈、判空、判满、获取栈顶元素、求栈的大小
2> 自行封装一个循环顺序队列的类,包含私有成员属性:存放队列的数组、队头位置、队尾位置
成员函数完成:构造函数、析构函数、拷贝构造函数、入队、出队、清空队列、判空、判满、求队列大小
1:
#include <iostream>
#define MAX 128using namespace std;
class Stack_s
{
private:int *p=new int[MAX];//栈的数组int top;//记录栈顶的变量
public://构造函数Stack_s(int t=-1){top=t;cout<<"无参构造函数"<<endl;}//析构函数~Stack_s(){cout<<"Stack::析构函数"<<endl;}//拷贝构造函数Stack_s(const Stack_s &other):p(other.p),top(other.top){cout<<"拷贝构造函数"<<endl;}//入栈int stack_push(int e){if(stack_full()){cout<<"入栈失败"<<endl;return -1;}top++;p[top]=e;cout<<"入栈成功"<<endl;return 0;}//出栈int stack_pop(){if(stack_empty()){cout<<"出栈失败"<<endl;return -1;}int e=p[top];top--;cout<<e<<" 出栈成功"<<endl;return 0;}//清空栈int stack_delete(){while(top!=-1){stack_pop();}delete [] p;p=nullptr;cout<<"清空栈成功"<<endl;return 0;}//判空bool stack_empty(){if(top==-1){cout<<"栈空"<<endl;return 1;}return 0;}//判满bool stack_full(){if(top==MAX-1){cout<<"栈满了"<<endl;return 1;}return 0;return 0;}//获取栈顶元素int stack_gettop(){cout<<"栈顶元素是:"<<p[top]<<endl;return 0;}//栈的大小void stack_getsize(){cout<<"栈的大小为:"<<top+1<<endl;}void show(int i){cout<<p[i]<<" ";}
};
int main()
{Stack_s s1;int e;int s;s1.stack_empty();cout<<"请输入要入栈的个数:";cin>>s;for(int i=0;i<s;i++){cout<<"请输入要入栈的元素:";cin>>e;s1.stack_push(e);}s1.stack_gettop();s1.stack_getsize();for(int i=0;i<s;i++){s1.show(i);}cout<<endl;s1.stack_delete();return 0;
}
2:
#include <iostream>
#define MAX 128using namespace std;
class Queue_q
{
private:int *p=new int[MAX];//队列的数组int tail;//记录队尾元素int head;//记录对头元素
public://构造函数Queue_q(int t=0){head=t;tail=t;cout<<"无参构造函数"<<endl;}//析构函数~Queue_q(){cout<<"Stack::析构函数"<<endl;}//拷贝构造函数Queue_q(const Queue_q &other):p(other.p),tail(other.tail),head(other.head){cout<<"拷贝构造函数"<<endl;}//入队int queue_push(int e){if(queue_full()){cout<<"入队失败"<<endl;return -1;}p[tail]=e;tail++;cout<<"入队成功"<<endl;return 0;}//出队int queue_pop(){if(queue_empty()){cout<<"出队失败"<<endl;return -1;}int e=p[head];head=(head+1)%MAX;cout<<e<<" 出队成功"<<endl;return 0;}//清空队列int queue_delete(){while(head!=tail){queue_pop();}delete [] p;p=nullptr;cout<<"清空队列成功"<<endl;return 0;}//判空bool queue_empty(){if(head==tail){cout<<"队列空"<<endl;return 1;}return 0;}//判满bool queue_full(){if((tail+1)==0){cout<<"队列满了"<<endl;return 1;}return 0;}//队列的大小void queue_getsize(){int size;size=(tail-head+MAX)%MAX;cout<<"队的大小为:"<<size<<endl;}void show(int i){cout<<p[i]<<" ";}
};
int main()
{Queue_q q1;int e;int s;q1.queue_empty();cout<<"请输入要入队的个数:";cin>>s;for(int i=0;i<s;i++){cout<<"请输入要入队的元素:";cin>>e;q1.queue_push(e);}q1.queue_getsize();for(int i=0;i<s;i++){q1.show(i);}cout<<endl;q1.queue_delete();return 0;
}
思维导图: