1> 自行封装一个栈的类,包含私有成员属性:栈的数组、记录栈顶的变量
成员函数完成:构造函数、析构函数、拷贝构造函数、入栈、出栈、清空栈、判空、判满、获取栈顶元素、求栈的大小
#include <iostream>using namespace std;class Stack
{
private:int data[8];int top=-1;public://构造函数Stack(){}//构析函数~Stack(){}//拷贝构造函数Stack(const Stack &other){}//判空bool stack_empty(Stack *p){if(p->top==-1){return 1;}return 0;}//判满bool stack_full(Stack *p){if(p->top==7){return 1;}return 0;}//入栈void stack_push(Stack *p,int e){if(NULL==p||stack_full(p)){return;}p->top++;p->data[p->top]=e;cout<<e<<endl;cout<<"入栈成功"<<endl;return ;}//出栈void stack_pop(Stack *p){if(NULL==p||stack_empty(p)){return ;}int e=p->data[p->top];cout<<e<<"出栈成功"<<endl;p->top--;return;}//销毁栈void stack_free(Stack *p){if(NULL==p){return ;}delete p;p=nullptr;cout<<"销毁成功"<<endl;return ;}//获取栈顶元素void stack_gettop(Stack *p){if(NULL==p){return ;}int e = p->data[p->top];cout<<"栈顶元素为"<<e<<endl;return ;}//求栈的大小void stack_size(Stack *p){if(NULL==p){return ;}cout<<"栈的大小为"<<p->top+1<<endl;}void stack_show(Stack *p){for(int i=0;i<=p->top;i++){cout<<" "<<p->data[i];}cout<<endl;return ;}
};int main()
{//初始化Stack zhan;//定义一个Stack *p=new Stack(zhan);//入栈zhan.stack_push(p,812);zhan.stack_push(p,627);zhan.stack_push(p,908);zhan.stack_push(p,929);zhan.stack_push(p,199);zhan.stack_show(p);cout<<"*******************************"<<endl;//出栈zhan.stack_pop(p);zhan.stack_pop(p);zhan.stack_pop(p);zhan.stack_show(p);//获取栈顶元素zhan.stack_gettop(p);//求栈大小zhan.stack_size(p);//销毁栈zhan.stack_free(p);return 0;
}
2> 自行封装一个循环顺序队列的类,包含私有成员属性:存放队列的数组、队头位置、队尾位置
成员函数完成:构造函数、析构函数、拷贝构造函数、入队、出队、清空队列、判空、判满、求队列大小
#include <iostream>using namespace std;class Queue
{
private:int data[8];int front=0;int tail=0;public://构造函数Queue(){}//构析函数~Queue(){}//拷贝构造函数Queue(const Queue &other){}//判空int queue_empty(Queue *p){if(NULL==p){cout<<"队列不合法"<<endl;return -1;}return 0;}//判满int queue_full(Queue *p){if(NULL==p){cout<<"所给队列不和发"<<endl;return -1;}return 0;}//入队void queue_push(Queue *p,int e){if(NULL==p||queue_full(p)){cout<<"入队失败"<<endl;return ;}p->data[p->tail]=e;p->tail=(p->tail+1)%8;cout<<"入队成功"<<endl;return ;}//出队void queue_pop(Queue *p){if(NULL==p||queue_empty(p)){cout<<"出队失败"<<endl;return ;}cout<<p->data[p->front]<<"出队成功"<<endl;p->front=(p->front+1)%8;return ;}//求队列长度void queue_size(Queue *p){if(NULL==p){cout<<"所给队列不合法"<<endl;return ;}cout<<"队列长度为"<<(p->tail+8-p->front)%8<<endl;return ;}//销毁队列void queue_free(Queue *p){if(NULL!=p){free(p);p=NULL;cout<<"释放成功"<<endl;return ;}cout<<"所给队列不合法"<<endl;return ;}//遍历void queue_show(Queue *p){for(int i=p->front;i!=p->tail;i=(i+1)%8){cout<<p->data[i]<<" ";}cout<<endl;}
};
int main()
{//定义一个队列Queue dl;//创建指针 申请空间Queue *p=new Queue(dl);//入队dl.queue_push(p,8);dl.queue_push(p,60);dl.queue_push(p,19);dl.queue_push(p,627);dl.queue_push(p,78);dl.queue_push(p,1);dl.queue_push(p,2);dl.queue_show(p);cout<<"**********************"<<endl;//出队dl.queue_pop(p);dl.queue_pop(p);dl.queue_pop(p);dl.queue_show(p);cout<<"**********************"<<endl;//求队列长度dl.queue_size(p);//销毁队列dl.queue_free(p);return 0;
}