stack 模板类
#include <iostream>
using namespace std;
template<typename T>
class MySta
{
private:
T* top1;
T* end1;
public:
MySta(int size=1)
{
top1=new T[size];
end1=top1;
}
~MySta()
{
delete []end1;
top1=end1=NULL;
}
int size()
{
return top1-end1;
}
MySta(const MySta& other)
{
int size=other.size()+1;
int len=size-1;
end1=new T[size];
memcpy(end1,other.end1,len*sizeof(T));
top1=end1+len;
}
MySta& operator=(const MySta& other)
{
int size=other.size()+1;
T *temp=new T[size];
memcpy(temp,other.end1,size*sizeof(T));
delete []end1;
end1=temp;
top1=end1+size;
}
T top()const
{
return *(top1-1);
}
bool empty()
{
return top1==end1;
}
void push(const T val)
{
int size=this->size()+1;
T* temp=new T[size];
memcpy(temp,end1,(size-1)*sizeof(T));
delete []end1;
end1=temp;
top1=end1+size-1;
*top1=val;
top1++;
}
void pop()
{
if(empty())
{
cout<<"栈表空"<<endl;
return;
}
top1--;
int size=this->size();
T* temp=new T[size];
memcpy(temp,end1,size*sizeof(T));
delete []end1;
end1=temp;
top1=end1+size;
}
};
int main()
{
MySta<int> q1;
cout<<q1.size()<<endl;
for(int i=0;i<20;i++)
{
q1.push(i);
cout<<q1.size()<<endl;
}
while(!(q1.empty()))
{
cout<<q1.top()<<" ";
q1.pop();
}
return 0;
}
queue 模板类
#include <iostream>
using namespace std;
template<typename T>
class MyQue
{
private:
T* first;
T* last;
public:
MyQue(int size=1)
{
first=new T[size];
last=first;
}
~MyQue()
{
delete []first;
first=last=NULL;
}
int size()
{
return last-first;
}
MyQue(const MyQue& other)
{
int size=other.size()+1;
int len=size-1;
first=new T[size];
memcpy(first,other.first,len*sizeof(T));
last=first+len;
}
MyQue& operator=(const MyQue& other)
{
int size=other.size()+1;
T *temp=new T[size];
memcpy(temp,other.first,size*sizeof(T));
delete []first;
first=temp;
last=first+size;
}
T front()const
{
return *first;
}
T back()const
{
return *last;
}
bool empty()
{
return last==first;
}
void push(const T val)
{
int size=this->size()+1;
T* temp=new T[size];
memcpy(temp,first,(size-1)*sizeof(T));
delete []first;
first=temp;
last=first+size-1;
*last=val;
last++;
}
void pop()
{
if(empty())
{
cout<<"栈表空"<<endl;
return;
}
first++;
int size=this->size();
T* temp=new T[size];
memcpy(temp,first,size*sizeof(T));
delete []first;
first=temp;
last=first+size;
}
};
int main()
{
MyQue<int> q1;
cout<<q1.size()<<endl;
for(int i=0;i<20;i++)
{
q1.push(i);
cout<<q1.size()<<endl;
}
while(!(q1.empty()))
{
cout<<q1.front()<<" ";
q1.pop();
}
return 0;
}