将之前定义的栈类和队列类都实现成模板类
栈:
#include <iostream>
#define MAX 128using namespace std;template<typename T,typename C>
class Stack
{
private:T top; //栈顶元素的下标C *data; //指向堆区空间public:Stack():top(-1),data(new C[MAX]) {} //无参构造//析构函数~Stack(){delete[] data;cout<<"析构函数"<<endl;}//拷贝构造函数Stack(const Stack &other):top(other.top),data(new T(*other.data)){for(int i=0;i<=top;i++){data[i]=other.data[i];}cout<<"拷贝构造函数"<<endl;}//入栈int Stack_push(C e){top++;data[top]=e;cout<<"入栈成功"<<endl;return 0;}//出栈int Stack_pop(){top--;cout<<"出栈成功"<<endl;return 0;}//清空栈void Stack_clear(){top=-1;return;}//判空bool Stack_empty(){return top==-1;}//判满bool Stack_full(){return top==MAX-1;}//获取栈顶元素C & Stack_top(){return data[top];}//求栈的大小int Stack_size(){return top+1;}
};int main()
{Stack<int,int> n1;n1.Stack_push(1);n1.Stack_push(2);cout<<"栈的大小为"<<n1.Stack_size()<<endl;cout<<"栈顶元素为"<<n1.Stack_top()<<endl;Stack<int,string> n2;n2.Stack_push("hello");n2.Stack_push(" world");cout<<"栈的大小为"<<n2.Stack_size()<<endl;cout<<"栈顶元素为"<<n2.Stack_top()<<endl;return 0;
}
运行结果:
队列:
代码:
#include <iostream>
#define MAX 128using namespace std;template<typename C>
class queue
{
private:int front;int tail;C data[MAX];public://构造函数queue():front(0),tail(0){cout<<"构造函数"<<endl;}//析构函数~queue(){cout<<"析构函数"<<endl;}//拷贝构造函数queue(const queue &other ):data(new C(*other.data)){int index=front;while(index!=tail){data[index]=other.data[index];index=(index+1)%128;}cout<<"拷贝构造函数"<<endl;}//入队int queue_push(C e){if(queue_full()){return -1;}data[tail]=e;tail=(tail+1)%128;return 0;}//出队int queue_pop(){if(queue_empty()){return -1;}front=(front+1)%128;return 0;}//清空队列void queue_delete(){tail=front=0;}//判空bool queue_empty(){return front==tail;}//判满bool queue_full(){return (tail+1)%128==front;}//求队列的大小int queue_size(){return (tail-front+128)%128;}//遍历void queue_show(){for(int i=front;i!=tail;i=(i+1)%128){cout<<data[i]<<" ";}putchar(10);}
};
int main()
{queue<int> n1;n1.queue_push(1);n1.queue_push(2);n1.queue_show();queue<string> n2;n2.queue_push("hello");n2.queue_push(" world");n2.queue_show();return 0;
}
运行结果:
思维导图