栈类实现成模板类
#include <iostream>
using namespace std;
template <typename T>
class Mystack
{
private:
T *ptr;
int size;
int top;
public:
//无参构造函数
Mystack<T>():ptr(new T[10]),top(-1){};
//有参构造函数
Mystack<T>(int s)
{
ptr=new T[size];
size=s;
top=-1;
cout<<"有参构造函数"<<endl;
}
//析构函数
~Mystack()
{
delete []ptr;
cout<<"析构函数"<<endl;
}
//拷贝赋值函数
Mystack<T>&operator = (const Mystack<T>&other)
{
if(this == &other)
{
return *this;
}
delete []ptr;
return strncat(this->ptr,&other.ptr,size);
}
//判空
bool empty()
{
return top == -1;
}
//判满
bool full()
{
return top== size-1;
}
//获取大小
int getsize()
{
return top+1;
}
//入栈
int push(T pos)
{
if(top == size -1)
{
return -1;
}
ptr[++top]= pos;
return 0;
}
//出栈
void pop()
{
if(top ==-1)
{
return;
}
top--;
}
//获取栈顶元素
T& gettop()
{
return ptr[top];
}
//遍历打印
void show()
{
if(top == -1)
return;
for(int i=0;i<=top;i++)
{
cout<<ptr[i]<<" ";
}
cout<<endl;
}
};
int main()
{
Mystack<int> m1(10);
m1.push(5);
m1.push(9);
m1.show();
Mystack<double> m2(10);
m2.push(2.3);
m2.push(6.9);
m2.show();
return 0;
}
队列类实现成模板类
#include <iostream>
using namespace std;
template<typename T>
class Queue
{
private:
int size; //队列大小
int front; //队头
int rear; //队尾
T *ptr; //队列的首地址
public:
//无参构造
Queue(){};
//有参构造
Queue(int s)
{
size=s;
ptr=new T[size];
front=0;
rear=0;
cout<<"有参构造"<<endl;
}
//析构函数
~Queue()
{
delete []ptr;
cout<<"析构函数"<<endl;
};
//拷贝赋值函数
Queue &operator = (const Queue &other)
{
if(this == &other)
{
return *this;
}
delete []ptr;
return strncat(this->ptr,&other.ptr,size);
}
bool empty()
{
return front == -1 && rear == -1;
}
bool full()
{
return (rear + 1) % size == front;
}
int get_size()
{
if (empty()) // 如果队列为空
{
return 0; // 返回队列大小为0
}
if (front <= rear) // 如果队头位置小于等于队尾位置
{
return rear - front + 1; // 返回队列大小为队尾位置减去队头位置再加1
}
else
{
return size - front + rear + 1; // 返回队列大小为队列容量减去队头位置再加上队尾位置再加1
}
}
int push(T data)
{
if(full())
{
return -1;
}
ptr[rear] = data;
rear = (rear +1)%size;
return 0;
}
int pop()
{
if(empty())
{
return -1;
}
front = (front +1)%size;
return 0;
}
void show()
{
if(empty())
{
return;
}
for(int i=front;i!=rear;i=(i+1)%size)
{
cout<<ptr[i]<<endl;
}
}
};
int main()
{
Queue<int> q1(10);
q1.push(5);
q1.push(6);
q1.get_size();
q1.show();
Queue<double> q2(10);
q2.push(5.5);
q2.push(8.5);
q2.show();
return 0;
}