1> 将之前定义的栈类和队列类都实现成模板类
栈的模块类
#include <iostream>
using namespace std;template <typename T>
class Stack
{
private:T data[40]={0};T top=-1;
public:Stack (){cout<<"这是构造函数"<<endl;}int stack_empty();int stack_full();int stack_push(int e);int stack_pop();int stack_size();int stack_top();int stack_fullpop();~Stack (){cout<<"这是析构函数"<<endl;}};template <typename T>
int Stack<T>::stack_empty()
{if(top==-1){cout<<"栈为空"<<endl;}return 1;
}template <typename T>
int Stack<T>::stack_full()
{if(top==39){cout<<"栈为满"<<endl;}return 1;
}
template <typename T>
int Stack<T>::stack_push(int e)
{stack_full();cout<<"进行入栈"<<endl;top++;data[top]=e;cout<<"入栈成功"<<endl;return 1;
}
template <typename T>
int Stack<T>::stack_pop()
{stack_empty();cout<<"进行出栈"<<endl;int e =data[top];top--;cout<<e<<"出栈成功"<<endl;return 1;
}
template <typename T>
int Stack<T>::stack_top()
{cout<<"栈顶元素为"<<data[top]<<endl;return 1;
}
template <typename T>
int Stack<T>::stack_size()
{return top+1;
}
template <typename T>
int Stack<T>::stack_fullpop()
{for(int i=top;i>-1;i--){cout<<data[i]<<"出栈成功"<<endl;}cout<<"清空栈成功"<<endl;return 1;}int main()
{Stack<int> s1;s1.stack_push(2);s1.stack_push(5);s1.stack_push(6);s1.stack_push(3);s1.stack_pop();cout<<"栈的大小"<<s1.stack_size()<<endl;s1.stack_top();s1.stack_fullpop();return 0;
}
队列的模块类
#include <iostream>
#define MAX 40using namespace std;
template <typename T>
class Queue
{
private:T data[MAX]={0};int front=0;int tail=0;
public:Queue(){cout<<"这里是构造函数"<<endl;}int queue_empty(); //判空int queue_full(); //判满int queue_push(int e); //入队int queue_pop(); //出队int queue_size(); // 队列长度int queue_fullpop(); //清空队列,全部出队~Queue(){cout<<"这是析构函数"<<endl;}};
template <typename T>
int Queue<T>::queue_empty() //判空
{return front==tail;}
template <typename T>
int Queue<T>::queue_full() //判满
{return (tail+1)%MAX ==front;}
template <typename T>
int Queue<T>::queue_push(int e) //入队
{queue_full();cout<<"进行入队"<<endl;data[tail]=e;tail++;cout<<"入队成功"<<endl;return 1;}
template <typename T>
int Queue<T>::queue_pop() //出队
{queue_empty() ;cout<<"进行出队"<<endl;int pop=data[front];cout<<pop<<"出队成功"<<endl;front++;return 1;
}
template <typename T>
int Queue<T>::queue_size() // 队列长度
{return (tail+MAX-front)%MAX;
}template <typename T>
int Queue<T>::queue_fullpop() //清空队列,全部出队
{for(int i=front;i!=tail;i++){cout<<data[i]<<"出队成功"<<endl;}cout<<"清空队列成功"<<endl;return 1;
}int main()
{Queue<int> q1;q1.queue_push(8);q1.queue_push(9);q1.queue_push(6);q1.queue_push(5);q1.queue_push(8);q1.queue_pop();q1.queue_pop();int size=q1.queue_size();cout<<"队列长度为"<<size<<endl;q1.queue_fullpop();return 0;
}
2.思维导图